Subversion Repositories FlightCtrl

Rev

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

Rev 1870 Rev 1872
1
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2
// + Copyright (c) 04.2007 Holger Buss
2
// + Copyright (c) 04.2007 Holger Buss
3
// + Nur für den privaten Gebrauch
3
// + Nur für den privaten Gebrauch
4
// + www.MikroKopter.com
4
// + www.MikroKopter.com
5
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
5
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6
// + Es gilt für das gesamte Projekt (Hardware, Software, Binärfiles, Sourcecode und Dokumentation),
6
// + Es gilt für das gesamte Projekt (Hardware, Software, Binärfiles, Sourcecode und Dokumentation),
7
// + dass eine Nutzung (auch auszugsweise) nur für den privaten (nicht-kommerziellen) Gebrauch zulässig ist.
7
// + dass eine Nutzung (auch auszugsweise) nur für den privaten (nicht-kommerziellen) Gebrauch zulässig ist.
8
// + Sollten direkte oder indirekte kommerzielle Absichten verfolgt werden, ist mit uns (info@mikrokopter.de) Kontakt
8
// + Sollten direkte oder indirekte kommerzielle Absichten verfolgt werden, ist mit uns (info@mikrokopter.de) Kontakt
9
// + bzgl. der Nutzungsbedingungen aufzunehmen.
9
// + bzgl. der Nutzungsbedingungen aufzunehmen.
10
// + Eine kommerzielle Nutzung ist z.B.Verkauf von MikroKoptern, Bestückung und Verkauf von Platinen oder Bausätzen,
10
// + Eine kommerzielle Nutzung ist z.B.Verkauf von MikroKoptern, Bestückung und Verkauf von Platinen oder Bausätzen,
11
// + Verkauf von Luftbildaufnahmen, usw.
11
// + Verkauf von Luftbildaufnahmen, usw.
12
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
12
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
13
// + Werden Teile des Quellcodes (mit oder ohne Modifikation) weiterverwendet oder veröffentlicht,
13
// + Werden Teile des Quellcodes (mit oder ohne Modifikation) weiterverwendet oder veröffentlicht,
14
// + unterliegen sie auch diesen Nutzungsbedingungen und diese Nutzungsbedingungen incl. Copyright müssen dann beiliegen
14
// + unterliegen sie auch diesen Nutzungsbedingungen und diese Nutzungsbedingungen incl. Copyright müssen dann beiliegen
15
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
15
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
16
// + Sollte die Software (auch auszugesweise) oder sonstige Informationen des MikroKopter-Projekts
16
// + Sollte die Software (auch auszugesweise) oder sonstige Informationen des MikroKopter-Projekts
17
// + auf anderen Webseiten oder sonstigen Medien veröffentlicht werden, muss unsere Webseite "http://www.mikrokopter.de"
17
// + auf anderen Webseiten oder sonstigen Medien veröffentlicht werden, muss unsere Webseite "http://www.mikrokopter.de"
18
// + eindeutig als Ursprung verlinkt werden
18
// + eindeutig als Ursprung verlinkt werden
19
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
19
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
20
// + Keine Gewähr auf Fehlerfreiheit, Vollständigkeit oder Funktion
20
// + Keine Gewähr auf Fehlerfreiheit, Vollständigkeit oder Funktion
21
// + Benutzung auf eigene Gefahr
21
// + Benutzung auf eigene Gefahr
22
// + Wir übernehmen keinerlei Haftung für direkte oder indirekte Personen- oder Sachschäden
22
// + Wir übernehmen keinerlei Haftung für direkte oder indirekte Personen- oder Sachschäden
23
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
23
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
24
// + Die Portierung der Software (oder Teile davon) auf andere Systeme (ausser der Hardware von www.mikrokopter.de) ist nur
24
// + Die Portierung der Software (oder Teile davon) auf andere Systeme (ausser der Hardware von www.mikrokopter.de) ist nur
25
// + mit unserer Zustimmung zulässig
25
// + mit unserer Zustimmung zulässig
26
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
26
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
27
// + Die Funktion printf_P() unterliegt ihrer eigenen Lizenz und ist hiervon nicht betroffen
27
// + Die Funktion printf_P() unterliegt ihrer eigenen Lizenz und ist hiervon nicht betroffen
28
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
28
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
29
// + Redistributions of source code (with or without modifications) must retain the above copyright notice,
29
// + Redistributions of source code (with or without modifications) must retain the above copyright notice,
30
// + this list of conditions and the following disclaimer.
30
// + this list of conditions and the following disclaimer.
31
// +   * Neither the name of the copyright holders nor the names of contributors may be used to endorse or promote products derived
31
// +   * Neither the name of the copyright holders nor the names of contributors may be used to endorse or promote products derived
32
// +     from this software without specific prior written permission.
32
// +     from this software without specific prior written permission.
33
// +   * The use of this project (hardware, software, binary files, sources and documentation) is only permittet
33
// +   * The use of this project (hardware, software, binary files, sources and documentation) is only permittet
34
// +     for non-commercial use (directly or indirectly)
34
// +     for non-commercial use (directly or indirectly)
35
// +     Commercial use (for example: selling of MikroKopters, selling of PCBs, assembly, ...) is only permitted
35
// +     Commercial use (for example: selling of MikroKopters, selling of PCBs, assembly, ...) is only permitted
36
// +     with our written permission
36
// +     with our written permission
37
// +   * If sources or documentations are redistributet on other webpages, out webpage (http://www.MikroKopter.de) must be
37
// +   * If sources or documentations are redistributet on other webpages, out webpage (http://www.MikroKopter.de) must be
38
// +     clearly linked as origin
38
// +     clearly linked as origin
39
// +   * porting to systems other than hardware from www.mikrokopter.de is not allowed
39
// +   * porting to systems other than hardware from www.mikrokopter.de is not allowed
40
// +  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
40
// +  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
41
// +  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41
// +  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42
// +  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
42
// +  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43
// +  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
43
// +  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
44
// +  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
44
// +  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
45
// +  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
45
// +  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
46
// +  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
46
// +  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
47
// +  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN// +  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
47
// +  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN// +  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
48
// +  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
48
// +  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
49
// +  POSSIBILITY OF SUCH DAMAGE.
49
// +  POSSIBILITY OF SUCH DAMAGE.
50
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
50
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
51
 
51
 
52
/************************************************************************/
52
/************************************************************************/
53
/* Flight Attitude                                                      */
53
/* Flight Attitude                                                      */
54
/************************************************************************/
54
/************************************************************************/
55
 
55
 
56
#include <stdlib.h>
56
#include <stdlib.h>
57
#include <avr/io.h>
57
#include <avr/io.h>
58
 
58
 
59
#include "attitude.h"
59
#include "attitude.h"
60
#include "dongfangMath.h"
60
#include "dongfangMath.h"
61
 
61
 
62
// For scope debugging only!
62
// For scope debugging only!
63
#include "rc.h"
63
#include "rc.h"
64
 
64
 
65
// where our main data flow comes from.
65
// where our main data flow comes from.
66
#include "analog.h"
66
#include "analog.h"
67
 
67
 
68
#include "configuration.h"
68
#include "configuration.h"
69
#include "output.h"
69
#include "output.h"
70
 
70
 
71
// Some calculations are performed depending on some stick related things.
71
// Some calculations are performed depending on some stick related things.
72
#include "controlMixer.h"
72
#include "controlMixer.h"
73
 
73
 
74
// For Servo_On / Off
74
// For Servo_On / Off
75
// #include "timer2.h"
75
// #include "timer2.h"
76
 
76
 
77
#define CHECK_MIN_MAX(value, min, max) {if(value < min) value = min; else if(value > max) value = max;}
77
#define CHECK_MIN_MAX(value, min, max) {if(value < min) value = min; else if(value > max) value = max;}
78
 
78
 
79
/*
79
/*
80
 * Gyro readings, as read from the analog module. It would have been nice to flow
80
 * Gyro readings, as read from the analog module. It would have been nice to flow
81
 * them around between the different calculations as a struct or array (doing
81
 * them around between the different calculations as a struct or array (doing
82
 * things functionally without side effects) but this is shorter and probably
82
 * things functionally without side effects) but this is shorter and probably
83
 * faster too.
83
 * faster too.
84
 * The variables are overwritten at each attitude calculation invocation - the values
84
 * The variables are overwritten at each attitude calculation invocation - the values
85
 * are not preserved or reused.
85
 * are not preserved or reused.
86
 */
86
 */
87
int16_t rate_ATT[2], yawRate;
87
int16_t rate_ATT[2], yawRate;
88
 
88
 
89
// With different (less) filtering
89
// With different (less) filtering
90
int16_t rate_PID[2];
90
int16_t rate_PID[2];
91
int16_t differential[2];
91
int16_t differential[2];
92
 
92
 
93
/*
93
/*
94
 * Gyro readings, after performing "axis coupling" - that is, the transfomation
94
 * Gyro readings, after performing "axis coupling" - that is, the transfomation
95
 * of rotation rates from the airframe-local coordinate system to a ground-fixed
95
 * of rotation rates from the airframe-local coordinate system to a ground-fixed
96
 * coordinate system. If axis copling is disabled, the gyro readings will be
96
 * coordinate system. If axis copling is disabled, the gyro readings will be
97
 * copied into these directly.
97
 * copied into these directly.
98
 * These are global for the same pragmatic reason as with the gyro readings.
98
 * These are global for the same pragmatic reason as with the gyro readings.
99
 * The variables are overwritten at each attitude calculation invocation - the values
99
 * The variables are overwritten at each attitude calculation invocation - the values
100
 * are not preserved or reused.
100
 * are not preserved or reused.
101
 */
101
 */
102
int16_t ACRate[2], ACYawRate;
102
int16_t ACRate[2], ACYawRate;
103
 
103
 
104
/*
104
/*
105
 * Gyro integrals. These are the rotation angles of the airframe compared to the
105
 * Gyro integrals. These are the rotation angles of the airframe compared to the
106
 * horizontal plane, yaw relative to yaw at start.
106
 * horizontal plane, yaw relative to yaw at start.
107
 */
107
 */
108
int32_t angle[2], yawAngleDiff;
108
int32_t angle[2], yawAngleDiff;
109
 
109
 
110
int readingHeight = 0;
110
int readingHeight = 0;
111
 
111
 
112
// Yaw angle and compass stuff.
112
// Yaw angle and compass stuff.
113
 
113
 
114
// This is updated/written from MM3. Negative angle indicates invalid data.
114
// This is updated/written from MM3. Negative angle indicates invalid data.
115
int16_t compassHeading = -1;
115
int16_t compassHeading = -1;
116
 
116
 
117
// This is NOT updated from MM3. Negative angle indicates invalid data.
117
// This is NOT updated from MM3. Negative angle indicates invalid data.
118
int16_t compassCourse = -1;
118
int16_t compassCourse = -1;
119
 
119
 
120
// The difference between the above 2 (heading - course) on a -180..179 degree interval.
120
// The difference between the above 2 (heading - course) on a -180..179 degree interval.
121
// Not necessary. Never read anywhere.
121
// Not necessary. Never read anywhere.
122
// int16_t compassOffCourse = 0;
122
// int16_t compassOffCourse = 0;
123
 
123
 
124
uint8_t updateCompassCourse = 0;
124
uint8_t updateCompassCourse = 0;
125
uint8_t compassCalState = 0;
125
uint8_t compassCalState = 0;
126
uint16_t ignoreCompassTimer = 500;
126
uint16_t ignoreCompassTimer = 500;
127
 
127
 
128
int32_t yawGyroHeading; // Yaw Gyro Integral supported by compass
128
int32_t yawGyroHeading; // Yaw Gyro Integral supported by compass
129
int16_t yawGyroDrift;
129
int16_t yawGyroDrift;
130
 
130
 
131
#define PITCHROLLOVER180 (GYRO_DEG_FACTOR_PITCHROLL * 180L)
131
#define PITCHROLLOVER180 (GYRO_DEG_FACTOR_PITCHROLL * 180L)
132
#define PITCHROLLOVER360 (GYRO_DEG_FACTOR_PITCHROLL * 360L)
132
#define PITCHROLLOVER360 (GYRO_DEG_FACTOR_PITCHROLL * 360L)
133
#define YAWOVER360       (GYRO_DEG_FACTOR_YAW * 360L)
133
#define YAWOVER360       (GYRO_DEG_FACTOR_YAW * 360L)
134
 
134
 
135
int16_t correctionSum[2] = { 0, 0 };
135
int16_t correctionSum[2] = { 0, 0 };
136
 
136
 
137
// For NaviCTRL use.
137
// For NaviCTRL use.
138
int16_t averageAcc[2] = { 0, 0 }, averageAccCount = 0;
138
int16_t averageAcc[2] = { 0, 0 }, averageAccCount = 0;
139
 
139
 
140
/*
140
/*
141
 * Experiment: Compensating for dynamic-induced gyro biasing.
141
 * Experiment: Compensating for dynamic-induced gyro biasing.
142
 */
142
 */
143
int16_t driftComp[2] = { 0, 0 }, driftCompYaw = 0;
143
int16_t driftComp[2] = { 0, 0 }, driftCompYaw = 0;
144
// int16_t savedDynamicOffsetPitch = 0, savedDynamicOffsetRoll = 0;
144
// int16_t savedDynamicOffsetPitch = 0, savedDynamicOffsetRoll = 0;
145
// int32_t dynamicCalPitch, dynamicCalRoll, dynamicCalYaw;
145
// int32_t dynamicCalPitch, dynamicCalRoll, dynamicCalYaw;
146
// int16_t dynamicCalCount;
146
// int16_t dynamicCalCount;
147
 
147
 
148
/************************************************************************
148
/************************************************************************
149
 * Set inclination angles from the acc. sensor data.                    
149
 * Set inclination angles from the acc. sensor data.                    
150
 * If acc. sensors are not used, set to zero.                          
150
 * If acc. sensors are not used, set to zero.                          
151
 * TODO: One could use inverse sine to calculate the angles more        
151
 * TODO: One could use inverse sine to calculate the angles more        
152
 * accurately, but since: 1) the angles are rather small at times when
152
 * accurately, but since: 1) the angles are rather small at times when
153
 * it makes sense to set the integrals (standing on ground, or flying at  
153
 * it makes sense to set the integrals (standing on ground, or flying at  
154
 * constant speed, and 2) at small angles a, sin(a) ~= constant * a,    
154
 * constant speed, and 2) at small angles a, sin(a) ~= constant * a,    
155
 * it is hardly worth the trouble.                                      
155
 * it is hardly worth the trouble.                                      
156
 ************************************************************************/
156
 ************************************************************************/
157
 
157
 
158
int32_t getAngleEstimateFromAcc(uint8_t axis) {
158
int32_t getAngleEstimateFromAcc(uint8_t axis) {
159
  return GYRO_ACC_FACTOR * (int32_t) filteredAcc[axis];
159
  return GYRO_ACC_FACTOR * (int32_t) filteredAcc[axis];
160
}
160
}
161
 
161
 
162
void setStaticAttitudeAngles(void) {
162
void setStaticAttitudeAngles(void) {
163
#ifdef ATTITUDE_USE_ACC_SENSORS
163
#ifdef ATTITUDE_USE_ACC_SENSORS
164
  angle[PITCH] = getAngleEstimateFromAcc(PITCH);
164
  angle[PITCH] = getAngleEstimateFromAcc(PITCH);
165
  angle[ROLL] = getAngleEstimateFromAcc(ROLL);
165
  angle[ROLL] = getAngleEstimateFromAcc(ROLL);
166
#else
166
#else
167
  angle[PITCH] = angle[ROLL] = 0;
167
  angle[PITCH] = angle[ROLL] = 0;
168
#endif
168
#endif
169
}
169
}
170
 
170
 
171
/************************************************************************
171
/************************************************************************
172
 * Neutral Readings                                                    
172
 * Neutral Readings                                                    
173
 ************************************************************************/
173
 ************************************************************************/
174
void attitude_setNeutral(void) {
174
void attitude_setNeutral(void) {
175
  // Servo_Off(); // disable servo output. TODO: Why bother? The servos are going to make a jerk anyway.
175
  // Servo_Off(); // disable servo output. TODO: Why bother? The servos are going to make a jerk anyway.
176
  dynamicParams.AxisCoupling1 = dynamicParams.AxisCoupling2 = 0;
176
  dynamicParams.AxisCoupling1 = dynamicParams.AxisCoupling2 = 0;
177
 
177
 
178
  driftComp[PITCH] = driftComp[ROLL] = yawGyroDrift = driftCompYaw = 0;
178
  driftComp[PITCH] = driftComp[ROLL] = yawGyroDrift = driftCompYaw = 0;
179
  correctionSum[PITCH] = correctionSum[ROLL] = 0;
179
  correctionSum[PITCH] = correctionSum[ROLL] = 0;
180
 
180
 
181
  // Calibrate hardware.
181
  // Calibrate hardware.
182
  analog_calibrate();
182
  analog_calibrate();
183
 
183
 
184
  // reset gyro integrals to acc guessing
184
  // reset gyro integrals to acc guessing
185
  setStaticAttitudeAngles();
185
  setStaticAttitudeAngles();
186
  yawAngleDiff = 0;
186
  yawAngleDiff = 0;
187
 
187
 
188
  // update compass course to current heading
188
  // update compass course to current heading
189
  compassCourse = compassHeading;
189
  compassCourse = compassHeading;
190
 
190
 
191
  // Inititialize YawGyroIntegral value with current compass heading
191
  // Inititialize YawGyroIntegral value with current compass heading
192
  yawGyroHeading = (int32_t) compassHeading * GYRO_DEG_FACTOR_YAW;
192
  yawGyroHeading = (int32_t) compassHeading * GYRO_DEG_FACTOR_YAW;
193
 
193
 
194
  // Servo_On(); //enable servo output
194
  // Servo_On(); //enable servo output
195
}
195
}
196
 
196
 
197
/************************************************************************
197
/************************************************************************
198
 * Get sensor data from the analog module, and release the ADC          
198
 * Get sensor data from the analog module, and release the ADC          
199
 * TODO: Ultimately, the analog module could do this (instead of dumping
199
 * TODO: Ultimately, the analog module could do this (instead of dumping
200
 * the values into variables).
200
 * the values into variables).
201
 * The rate variable end up in a range of about [-1024, 1023].
201
 * The rate variable end up in a range of about [-1024, 1023].
202
 *************************************************************************/
202
 *************************************************************************/
203
void getAnalogData(void) {
203
void getAnalogData(void) {
204
  uint8_t axis;
204
  uint8_t axis;
205
 
205
 
206
  for (axis = PITCH; axis <= ROLL; axis++) {
206
  for (axis = PITCH; axis <= ROLL; axis++) {
207
    rate_PID[axis] = gyro_PID[axis] / HIRES_GYRO_INTEGRATION_FACTOR + driftComp[axis];
207
    rate_PID[axis] = gyro_PID[axis] / HIRES_GYRO_INTEGRATION_FACTOR + driftComp[axis];
208
    rate_ATT[axis] = gyro_ATT[axis] / HIRES_GYRO_INTEGRATION_FACTOR + driftComp[axis];
208
    rate_ATT[axis] = gyro_ATT[axis] / HIRES_GYRO_INTEGRATION_FACTOR + driftComp[axis];
209
    differential[axis] = gyroD[axis];
209
    differential[axis] = gyroD[axis];
210
    averageAcc[axis] += acc[axis];
210
    averageAcc[axis] += acc[axis];
211
  }
211
  }
212
 
212
 
213
  averageAccCount++;
213
  averageAccCount++;
214
  yawRate = yawGyro + driftCompYaw;
214
  yawRate = yawGyro + driftCompYaw;
215
 
215
 
216
  // We are done reading variables from the analog module.
216
  // We are done reading variables from the analog module.
217
  // Interrupt-driven sensor reading may restart.
217
  // Interrupt-driven sensor reading may restart.
218
  analogDataReady = 0;
218
  analogDataReady = 0;
219
  J4HIGH;
-
 
220
  analog_start();
219
  analog_start();
221
}
220
}
222
 
221
 
223
/*
222
/*
224
 * This is the standard flight-style coordinate system transformation
223
 * This is the standard flight-style coordinate system transformation
225
 * (from airframe-local axes to a ground-based system). For some reason
224
 * (from airframe-local axes to a ground-based system). For some reason
226
 * the MK uses a left-hand coordinate system. The tranformation has been
225
 * the MK uses a left-hand coordinate system. The tranformation has been
227
 * changed accordingly.
226
 * changed accordingly.
228
 */
227
 */
229
void trigAxisCoupling(void) {
228
void trigAxisCoupling(void) {
230
  int16_t cospitch = int_cos(angle[PITCH]);
229
  int16_t cospitch = int_cos(angle[PITCH]);
231
  int16_t cosroll = int_cos(angle[ROLL]);
230
  int16_t cosroll = int_cos(angle[ROLL]);
232
  int16_t sinroll = int_sin(angle[ROLL]);
231
  int16_t sinroll = int_sin(angle[ROLL]);
233
 
232
 
234
  ACRate[PITCH] = (((int32_t)rate_ATT[PITCH] * cosroll - (int32_t)yawRate
233
  ACRate[PITCH] = (((int32_t)rate_ATT[PITCH] * cosroll - (int32_t)yawRate
235
      * sinroll) >> MATH_UNIT_FACTOR_LOG);
234
      * sinroll) >> MATH_UNIT_FACTOR_LOG);
236
 
235
 
237
  ACRate[ROLL] = rate_ATT[ROLL] + (((((int32_t)rate_ATT[PITCH] * sinroll
236
  ACRate[ROLL] = rate_ATT[ROLL] + (((((int32_t)rate_ATT[PITCH] * sinroll
238
      + (int32_t)yawRate * cosroll) >> MATH_UNIT_FACTOR_LOG) * int_tan(
237
      + (int32_t)yawRate * cosroll) >> MATH_UNIT_FACTOR_LOG) * int_tan(
239
      angle[PITCH])) >> MATH_UNIT_FACTOR_LOG);
238
      angle[PITCH])) >> MATH_UNIT_FACTOR_LOG);
240
 
239
 
241
  ACYawRate = ((int32_t)rate_ATT[PITCH] * sinroll + (int32_t)yawRate * cosroll) / cospitch;
240
  ACYawRate = ((int32_t)rate_ATT[PITCH] * sinroll + (int32_t)yawRate * cosroll) / cospitch;
-
 
241
 
-
 
242
  ACYawRate = ((int32_t)rate_ATT[PITCH] * sinroll + (int32_t)yawRate * cosroll) / cospitch;
242
}
243
}
243
 
244
 
244
// 480 usec with axis coupling - almost no time without.
245
// 480 usec with axis coupling - almost no time without.
245
void integrate(void) {
246
void integrate(void) {
246
  // First, perform axis coupling. If disabled xxxRate is just copied to ACxxxRate.
247
  // First, perform axis coupling. If disabled xxxRate is just copied to ACxxxRate.
247
  uint8_t axis;
248
  uint8_t axis;
-
 
249
 
248
  if (!looping && (staticParams.GlobalConfig & CFG_AXIS_COUPLING_ACTIVE)) {
250
  if (!looping && (staticParams.GlobalConfig & CFG_AXIS_COUPLING_ACTIVE)) {
249
    trigAxisCoupling();
251
    trigAxisCoupling();
250
  } else {
252
  } else {
251
    ACRate[PITCH] = rate_ATT[PITCH];
253
    ACRate[PITCH] = rate_ATT[PITCH];
252
    ACRate[ROLL] = rate_ATT[ROLL];
254
    ACRate[ROLL] = rate_ATT[ROLL];
253
    ACYawRate = yawRate;
255
    ACYawRate = yawRate;
254
  }
256
  }
255
 
257
 
256
  /*
258
  /*
257
   * Yaw
259
   * Yaw
258
   * Calculate yaw gyro integral (~ to rotation angle)
260
   * Calculate yaw gyro integral (~ to rotation angle)
259
   * Limit yawGyroHeading proportional to 0 deg to 360 deg
261
   * Limit yawGyroHeading proportional to 0 deg to 360 deg
260
   */
262
   */
261
  yawGyroHeading += ACYawRate;
263
  yawGyroHeading += ACYawRate;
262
  yawAngleDiff += yawRate;
264
  yawAngleDiff += yawRate;
263
 
265
 
264
  if (yawGyroHeading >= YAWOVER360) {
266
  if (yawGyroHeading >= YAWOVER360) {
265
    yawGyroHeading -= YAWOVER360; // 360 deg. wrap
267
    yawGyroHeading -= YAWOVER360; // 360 deg. wrap
266
  } else if (yawGyroHeading < 0) {
268
  } else if (yawGyroHeading < 0) {
267
    yawGyroHeading += YAWOVER360;
269
    yawGyroHeading += YAWOVER360;
268
  }
270
  }
269
 
271
 
270
  /*
272
  /*
271
   * Pitch axis integration and range boundary wrap.
273
   * Pitch axis integration and range boundary wrap.
272
   */
274
   */
273
  for (axis = PITCH; axis <= ROLL; axis++) {
275
  for (axis = PITCH; axis <= ROLL; axis++) {
274
    angle[axis] += ACRate[axis];
276
    angle[axis] += ACRate[axis];
275
    if (angle[axis] > PITCHROLLOVER180) {
277
    if (angle[axis] > PITCHROLLOVER180) {
276
      angle[axis] -= PITCHROLLOVER360;
278
      angle[axis] -= PITCHROLLOVER360;
277
    } else if (angle[axis] <= -PITCHROLLOVER180) {
279
    } else if (angle[axis] <= -PITCHROLLOVER180) {
278
      angle[axis] += PITCHROLLOVER360;
280
      angle[axis] += PITCHROLLOVER360;
279
    }
281
    }
280
  }
282
  }
281
}
283
}
282
 
284
 
283
/************************************************************************
285
/************************************************************************
284
 * A kind of 0'th order integral correction, that corrects the integrals
286
 * A kind of 0'th order integral correction, that corrects the integrals
285
 * directly. This is the "gyroAccFactor" stuff in the original code.
287
 * directly. This is the "gyroAccFactor" stuff in the original code.
286
 * There is (there) also a drift compensation
288
 * There is (there) also a drift compensation
287
 * - it corrects the differential of the integral = the gyro offsets.
289
 * - it corrects the differential of the integral = the gyro offsets.
288
 * That should only be necessary with drifty gyros like ENC-03.
290
 * That should only be necessary with drifty gyros like ENC-03.
289
 ************************************************************************/
291
 ************************************************************************/
290
void correctIntegralsByAcc0thOrder(void) {
292
void correctIntegralsByAcc0thOrder(void) {
291
  // TODO: Consider changing this to: Only correct when integrals are less than ...., or only correct when angular velocities
293
  // TODO: Consider changing this to: Only correct when integrals are less than ...., or only correct when angular velocities
292
  // are less than ....., or reintroduce Kalman.
294
  // are less than ....., or reintroduce Kalman.
293
  // Well actually the Z axis acc. check is not so silly.
295
  // Well actually the Z axis acc. check is not so silly.
294
  uint8_t axis;
296
  uint8_t axis;
295
  int32_t temp;
297
  int32_t temp;
296
  if (!looping && acc[Z] >= -dynamicParams.UserParams[7] && acc[Z]
298
  if (!looping && acc[Z] >= -dynamicParams.UserParams[7] && acc[Z]
297
      <= dynamicParams.UserParams[7]) {
299
      <= dynamicParams.UserParams[7]) {
298
    DebugOut.Digital[0] |= DEBUG_ACC0THORDER;
300
    DebugOut.Digital[0] |= DEBUG_ACC0THORDER;
299
 
301
 
300
    uint8_t permilleAcc = staticParams.GyroAccFactor; // NOTE!!! The meaning of this value has changed!!
302
    uint8_t permilleAcc = staticParams.GyroAccFactor; // NOTE!!! The meaning of this value has changed!!
301
    uint8_t debugFullWeight = 1;
303
    uint8_t debugFullWeight = 1;
302
    int32_t accDerived;
304
    int32_t accDerived;
303
 
305
 
304
    if ((controlYaw < -64) || (controlYaw > 64)) { // reduce further if yaw stick is active
306
    if ((controlYaw < -64) || (controlYaw > 64)) { // reduce further if yaw stick is active
305
      permilleAcc /= 2;
307
      permilleAcc /= 2;
306
      debugFullWeight = 0;
308
      debugFullWeight = 0;
307
    }
309
    }
308
 
310
 
309
    if ((maxControl[PITCH] > 64) || (maxControl[ROLL] > 64)) { // reduce effect during stick commands
311
    if ((maxControl[PITCH] > 64) || (maxControl[ROLL] > 64)) { // reduce effect during stick commands
310
      permilleAcc /= 2;
312
      permilleAcc /= 2;
311
      debugFullWeight = 0;
313
      debugFullWeight = 0;
312
    }
314
    }
313
 
315
 
314
    if (debugFullWeight)
316
    if (debugFullWeight)
315
      DebugOut.Digital[1] |= DEBUG_ACC0THORDER;
317
      DebugOut.Digital[1] |= DEBUG_ACC0THORDER;
316
    else
318
    else
317
      DebugOut.Digital[1] &= ~DEBUG_ACC0THORDER;
319
      DebugOut.Digital[1] &= ~DEBUG_ACC0THORDER;
318
 
320
 
319
    /*
321
    /*
320
     * Add to each sum: The amount by which the angle is changed just below.
322
     * Add to each sum: The amount by which the angle is changed just below.
321
     */
323
     */
322
    for (axis = PITCH; axis <= ROLL; axis++) {
324
    for (axis = PITCH; axis <= ROLL; axis++) {
323
      accDerived = getAngleEstimateFromAcc(axis);
325
      accDerived = getAngleEstimateFromAcc(axis);
324
      DebugOut.Analog[9 + axis] = (10 * accDerived) / GYRO_DEG_FACTOR_PITCHROLL;
326
      DebugOut.Analog[9 + axis] = (10 * accDerived) / GYRO_DEG_FACTOR_PITCHROLL;
325
 
327
 
326
      // 1000 * the correction amount that will be added to the gyro angle in next line.
328
      // 1000 * the correction amount that will be added to the gyro angle in next line.
327
      temp = angle[axis]; //(permilleAcc * (accDerived - angle[axis])) / 1000;
329
      temp = angle[axis]; //(permilleAcc * (accDerived - angle[axis])) / 1000;
328
      angle[axis] = ((int32_t) (1000L - permilleAcc) * temp
330
      angle[axis] = ((int32_t) (1000L - permilleAcc) * temp
329
          + (int32_t) permilleAcc * accDerived) / 1000L;
331
          + (int32_t) permilleAcc * accDerived) / 1000L;
330
      correctionSum[axis] += angle[axis] - temp;
332
      correctionSum[axis] += angle[axis] - temp;
331
    }
333
    }
332
  } else {
334
  } else {
333
    DebugOut.Digital[0] &= ~DEBUG_ACC0THORDER;
335
    DebugOut.Digital[0] &= ~DEBUG_ACC0THORDER;
334
    DebugOut.Digital[1] &= ~DEBUG_ACC0THORDER;
336
    DebugOut.Digital[1] &= ~DEBUG_ACC0THORDER;
335
    DebugOut.Analog[9] = 0;
337
    DebugOut.Analog[9] = 0;
336
    DebugOut.Analog[10] = 0;
338
    DebugOut.Analog[10] = 0;
337
 
339
 
338
    DebugOut.Analog[16] = 0;
340
    DebugOut.Analog[16] = 0;
339
    DebugOut.Analog[17] = 0;
341
    DebugOut.Analog[17] = 0;
340
    // experiment: Kill drift compensation updates when not flying smooth.
342
    // experiment: Kill drift compensation updates when not flying smooth.
341
    correctionSum[PITCH] = correctionSum[ROLL] = 0;
343
    correctionSum[PITCH] = correctionSum[ROLL] = 0;
342
  }
344
  }
343
}
345
}
344
 
346
 
345
/************************************************************************
347
/************************************************************************
346
 * This is an attempt to correct not the error in the angle integrals
348
 * This is an attempt to correct not the error in the angle integrals
347
 * (that happens in correctIntegralsByAcc0thOrder above) but rather the
349
 * (that happens in correctIntegralsByAcc0thOrder above) but rather the
348
 * cause of it: Gyro drift, vibration and rounding errors.
350
 * cause of it: Gyro drift, vibration and rounding errors.
349
 * All the corrections made in correctIntegralsByAcc0thOrder over
351
 * All the corrections made in correctIntegralsByAcc0thOrder over
350
 * DRIFTCORRECTION_TIME cycles are summed up. This number is
352
 * DRIFTCORRECTION_TIME cycles are summed up. This number is
351
 * then divided by DRIFTCORRECTION_TIME to get the approx.
353
 * then divided by DRIFTCORRECTION_TIME to get the approx.
352
 * correction that should have been applied to each iteration to fix
354
 * correction that should have been applied to each iteration to fix
353
 * the error. This is then added to the dynamic offsets.
355
 * the error. This is then added to the dynamic offsets.
354
 ************************************************************************/
356
 ************************************************************************/
355
// 2 times / sec. = 488/2
357
// 2 times / sec. = 488/2
356
#define DRIFTCORRECTION_TIME 256L
358
#define DRIFTCORRECTION_TIME 256L
357
void driftCorrection(void) {
359
void driftCorrection(void) {
358
  static int16_t timer = DRIFTCORRECTION_TIME;
360
  static int16_t timer = DRIFTCORRECTION_TIME;
359
  int16_t deltaCorrection;
361
  int16_t deltaCorrection;
-
 
362
  int16_t round;
360
  uint8_t axis;
363
  uint8_t axis;
-
 
364
 
-
 
365
  DebugOut.Analog[6] = (DRIFTCORRECTION_TIME + DRIFTCORRECTION_TIME/2) / DRIFTCORRECTION_TIME;
-
 
366
  DebugOut.Analog[7] = (-DRIFTCORRECTION_TIME + DRIFTCORRECTION_TIME/2) / DRIFTCORRECTION_TIME;
-
 
367
 
361
  if (!--timer) {
368
  if (!--timer) {
362
    timer = DRIFTCORRECTION_TIME;
369
    timer = DRIFTCORRECTION_TIME;
363
    for (axis = PITCH; axis <= ROLL; axis++) {
370
    for (axis = PITCH; axis <= ROLL; axis++) {
364
      // Take the sum of corrections applied, add it to delta
371
      // Take the sum of corrections applied, add it to delta
-
 
372
      if (correctionSum[axis] >=0)
365
      deltaCorrection = (correctionSum[axis] + DRIFTCORRECTION_TIME / 2)
373
        round = DRIFTCORRECTION_TIME / 2;
-
 
374
      else
366
          / DRIFTCORRECTION_TIME;
375
        round = -DRIFTCORRECTION_TIME / 2;
-
 
376
      deltaCorrection = (correctionSum[axis] + round) / DRIFTCORRECTION_TIME;
367
      // Add the delta to the compensation. So positive delta means, gyro should have higher value.
377
      // Add the delta to the compensation. So positive delta means, gyro should have higher value.
368
      driftComp[axis] += deltaCorrection / staticParams.GyroAccTrim;
378
      driftComp[axis] += deltaCorrection / staticParams.GyroAccTrim;
369
      CHECK_MIN_MAX(driftComp[axis], -staticParams.DriftComp, staticParams.DriftComp);
379
      CHECK_MIN_MAX(driftComp[axis], -staticParams.DriftComp, staticParams.DriftComp);
370
      // DebugOut.Analog[11 + axis] = correctionSum[axis];
380
      // DebugOut.Analog[11 + axis] = correctionSum[axis];
371
      DebugOut.Analog[16 + axis] = correctionSum[axis];
381
      DebugOut.Analog[16 + axis] = correctionSum[axis];
372
      DebugOut.Analog[18 + axis] = deltaCorrection / staticParams.GyroAccTrim;
-
 
373
      DebugOut.Analog[28 + axis] = driftComp[axis];
382
      DebugOut.Analog[28 + axis] = driftComp[axis];
374
 
383
 
375
      correctionSum[axis] = 0;
384
      correctionSum[axis] = 0;
376
    }
385
    }
377
  }
386
  }
378
}
387
}
379
 
388
 
380
/************************************************************************
389
/************************************************************************
381
 * Main procedure.
390
 * Main procedure.
382
 ************************************************************************/
391
 ************************************************************************/
383
void calculateFlightAttitude(void) {
392
void calculateFlightAttitude(void) {
384
  // part1: 550 usec.
-
 
385
  // part1a: 550 usec.
-
 
386
  // part1b: 60 usec.
-
 
387
  getAnalogData();
393
  getAnalogData();
388
  // end part1b
-
 
389
  integrate();
394
  integrate();
390
  // end part1a
-
 
391
 
-
 
392
  DebugOut.Analog[6] = stronglyFilteredAcc[PITCH];
-
 
393
  DebugOut.Analog[7] = stronglyFilteredAcc[ROLL];
-
 
394
  DebugOut.Analog[8] = stronglyFilteredAcc[Z];
-
 
395
 
395
 
396
  DebugOut.Analog[3] = rate_PID[PITCH];
396
  DebugOut.Analog[3] = rate_PID[PITCH];
397
  DebugOut.Analog[4] = rate_PID[ROLL];
397
  DebugOut.Analog[4] = rate_PID[ROLL];
398
  DebugOut.Analog[5] = yawRate;
398
  DebugOut.Analog[5] = yawRate;
399
 
399
 
400
#ifdef ATTITUDE_USE_ACC_SENSORS
400
#ifdef ATTITUDE_USE_ACC_SENSORS
401
  correctIntegralsByAcc0thOrder();
401
  correctIntegralsByAcc0thOrder();
402
  driftCorrection();
402
  driftCorrection();
403
#endif
403
#endif
404
  // end part1
-
 
405
}
404
}
406
 
405
 
407
void updateCompass(void) {
406
void updateCompass(void) {
408
  int16_t w, v, r, correction, error;
407
  int16_t w, v, r, correction, error;
409
 
408
 
410
  if (compassCalState && !(MKFlags & MKFLAG_MOTOR_RUN)) {
409
  if (compassCalState && !(MKFlags & MKFLAG_MOTOR_RUN)) {
411
    if (controlMixer_testCompassCalState()) {
410
    if (controlMixer_testCompassCalState()) {
412
      compassCalState++;
411
      compassCalState++;
413
      if (compassCalState < 5)
412
      if (compassCalState < 5)
414
        beepNumber(compassCalState);
413
        beepNumber(compassCalState);
415
      else
414
      else
416
        beep(1000);
415
        beep(1000);
417
    }
416
    }
418
  } else {
417
  } else {
419
    // get maximum attitude angle
418
    // get maximum attitude angle
420
    w = abs(angle[PITCH] / 512);
419
    w = abs(angle[PITCH] / 512);
421
    v = abs(angle[ROLL] / 512);
420
    v = abs(angle[ROLL] / 512);
422
    if (v > w)
421
    if (v > w)
423
      w = v;
422
      w = v;
424
    correction = w / 8 + 1;
423
    correction = w / 8 + 1;
425
    // calculate the deviation of the yaw gyro heading and the compass heading
424
    // calculate the deviation of the yaw gyro heading and the compass heading
426
    if (compassHeading < 0)
425
    if (compassHeading < 0)
427
      error = 0; // disable yaw drift compensation if compass heading is undefined
426
      error = 0; // disable yaw drift compensation if compass heading is undefined
428
    else if (abs(yawRate) > 128) { // spinning fast
427
    else if (abs(yawRate) > 128) { // spinning fast
429
      error = 0;
428
      error = 0;
430
    } else {
429
    } else {
431
      // compassHeading - yawGyroHeading, on a -180..179 deg interval.
430
      // compassHeading - yawGyroHeading, on a -180..179 deg interval.
432
      error = ((540 + compassHeading - (yawGyroHeading / GYRO_DEG_FACTOR_YAW))
431
      error = ((540 + compassHeading - (yawGyroHeading / GYRO_DEG_FACTOR_YAW))
433
          % 360) - 180;
432
          % 360) - 180;
434
    }
433
    }
435
    if (!ignoreCompassTimer && w < 25) {
434
    if (!ignoreCompassTimer && w < 25) {
436
      yawGyroDrift += error;
435
      yawGyroDrift += error;
437
      // Basically this gets set if we are in "fix" mode, and when starting.
436
      // Basically this gets set if we are in "fix" mode, and when starting.
438
      if (updateCompassCourse) {
437
      if (updateCompassCourse) {
439
        beep(200);
438
        beep(200);
440
        yawGyroHeading = (int32_t) compassHeading * GYRO_DEG_FACTOR_YAW;
439
        yawGyroHeading = (int32_t) compassHeading * GYRO_DEG_FACTOR_YAW;
441
        compassCourse = compassHeading; //(int16_t)(yawGyroHeading / GYRO_DEG_FACTOR_YAW);
440
        compassCourse = compassHeading; //(int16_t)(yawGyroHeading / GYRO_DEG_FACTOR_YAW);
442
        updateCompassCourse = 0;
441
        updateCompassCourse = 0;
443
      }
442
      }
444
    }
443
    }
445
    yawGyroHeading += (error * 8) / correction;
444
    yawGyroHeading += (error * 8) / correction;
446
 
445
 
447
    /*
446
    /*
448
     w = (w * dynamicParams.CompassYawEffect) / 32;
447
     w = (w * dynamicParams.CompassYawEffect) / 32;
449
     w = dynamicParams.CompassYawEffect - w;
448
     w = dynamicParams.CompassYawEffect - w;
450
     */
449
     */
451
    w = dynamicParams.CompassYawEffect - (w * dynamicParams.CompassYawEffect)
450
    w = dynamicParams.CompassYawEffect - (w * dynamicParams.CompassYawEffect)
452
        / 32;
451
        / 32;
453
 
452
 
454
    // As readable formula:
453
    // As readable formula:
455
    // w = dynamicParams.CompassYawEffect * (1-w/32);
454
    // w = dynamicParams.CompassYawEffect * (1-w/32);
456
 
455
 
457
    if (w >= 0) { // maxAttitudeAngle < 32
456
    if (w >= 0) { // maxAttitudeAngle < 32
458
      if (!ignoreCompassTimer) {
457
      if (!ignoreCompassTimer) {
459
        v = 64 + (maxControl[PITCH] + maxControl[ROLL]) / 8;
458
        v = 64 + (maxControl[PITCH] + maxControl[ROLL]) / 8;
460
        // yawGyroHeading - compassCourse on a -180..179 degree interval.
459
        // yawGyroHeading - compassCourse on a -180..179 degree interval.
461
        r
460
        r
462
            = ((540 + yawGyroHeading / GYRO_DEG_FACTOR_YAW - compassCourse)
461
            = ((540 + yawGyroHeading / GYRO_DEG_FACTOR_YAW - compassCourse)
463
                % 360) - 180;
462
                % 360) - 180;
464
        v = (r * w) / v; // align to compass course
463
        v = (r * w) / v; // align to compass course
465
        // limit yaw rate
464
        // limit yaw rate
466
        w = 3 * dynamicParams.CompassYawEffect;
465
        w = 3 * dynamicParams.CompassYawEffect;
467
        if (v > w)
466
        if (v > w)
468
          v = w;
467
          v = w;
469
        else if (v < -w)
468
        else if (v < -w)
470
          v = -w;
469
          v = -w;
471
        yawAngleDiff += v;
470
        yawAngleDiff += v;
472
      } else { // wait a while
471
      } else { // wait a while
473
        ignoreCompassTimer--;
472
        ignoreCompassTimer--;
474
      }
473
      }
475
    } else { // ignore compass at extreme attitudes for a while
474
    } else { // ignore compass at extreme attitudes for a while
476
      ignoreCompassTimer = 500;
475
      ignoreCompassTimer = 500;
477
    }
476
    }
478
  }
477
  }
479
}
478
}
480
 
479
 
481
/*
480
/*
482
 * This is part of an experiment to measure average sensor offsets caused by motor vibration,
481
 * This is part of an experiment to measure average sensor offsets caused by motor vibration,
483
 * and to compensate them away. It brings about some improvement, but no miracles.
482
 * and to compensate them away. It brings about some improvement, but no miracles.
484
 * As long as the left stick is kept in the start-motors position, the dynamic compensation
483
 * As long as the left stick is kept in the start-motors position, the dynamic compensation
485
 * will measure the effect of vibration, to use for later compensation. So, one should keep
484
 * will measure the effect of vibration, to use for later compensation. So, one should keep
486
 * the stick in the start-motors position for a few seconds, till all motors run (at the wrong
485
 * the stick in the start-motors position for a few seconds, till all motors run (at the wrong
487
 * speed unfortunately... must find a better way)
486
 * speed unfortunately... must find a better way)
488
 */
487
 */
489
/*
488
/*
490
 void attitude_startDynamicCalibration(void) {
489
 void attitude_startDynamicCalibration(void) {
491
 dynamicCalPitch = dynamicCalRoll = dynamicCalYaw = dynamicCalCount = 0;
490
 dynamicCalPitch = dynamicCalRoll = dynamicCalYaw = dynamicCalCount = 0;
492
 savedDynamicOffsetPitch = savedDynamicOffsetRoll = 1000;
491
 savedDynamicOffsetPitch = savedDynamicOffsetRoll = 1000;
493
 }
492
 }
494
 
493
 
495
 void attitude_continueDynamicCalibration(void) {
494
 void attitude_continueDynamicCalibration(void) {
496
 // measure dynamic offset now...
495
 // measure dynamic offset now...
497
 dynamicCalPitch += hiResPitchGyro;
496
 dynamicCalPitch += hiResPitchGyro;
498
 dynamicCalRoll += hiResRollGyro;
497
 dynamicCalRoll += hiResRollGyro;
499
 dynamicCalYaw += rawYawGyroSum;
498
 dynamicCalYaw += rawYawGyroSum;
500
 dynamicCalCount++;
499
 dynamicCalCount++;
501
 
500
 
502
 // Param6: Manual mode. The offsets are taken from Param7 and Param8.
501
 // Param6: Manual mode. The offsets are taken from Param7 and Param8.
503
 if (dynamicParams.UserParam6 || 1) { // currently always enabled.
502
 if (dynamicParams.UserParam6 || 1) { // currently always enabled.
504
 // manual mode
503
 // manual mode
505
 driftCompPitch = dynamicParams.UserParam7 - 128;
504
 driftCompPitch = dynamicParams.UserParam7 - 128;
506
 driftCompRoll = dynamicParams.UserParam8 - 128;
505
 driftCompRoll = dynamicParams.UserParam8 - 128;
507
 } else {
506
 } else {
508
 // use the sampled value (does not seem to work so well....)
507
 // use the sampled value (does not seem to work so well....)
509
 driftCompPitch = savedDynamicOffsetPitch = -dynamicCalPitch / dynamicCalCount;
508
 driftCompPitch = savedDynamicOffsetPitch = -dynamicCalPitch / dynamicCalCount;
510
 driftCompRoll = savedDynamicOffsetRoll = -dynamicCalRoll / dynamicCalCount;
509
 driftCompRoll = savedDynamicOffsetRoll = -dynamicCalRoll / dynamicCalCount;
511
 driftCompYaw = -dynamicCalYaw / dynamicCalCount;
510
 driftCompYaw = -dynamicCalYaw / dynamicCalCount;
512
 }
511
 }
513
 
512
 
514
 // keep resetting these meanwhile, to avoid accumulating errors.
513
 // keep resetting these meanwhile, to avoid accumulating errors.
515
 setStaticAttitudeIntegrals();
514
 setStaticAttitudeIntegrals();
516
 yawAngle = 0;
515
 yawAngle = 0;
517
 }
516
 }
518
 */
517
 */
519
 
518