Subversion Repositories FlightCtrl

Rev

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

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