Subversion Repositories FlightCtrl

Rev

Rev 2051 | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 2051 Rev 2052
1
#include <stdlib.h>
1
#include <stdlib.h>
2
#include <avr/io.h>
2
#include <avr/io.h>
3
 
3
 
4
#include "attitude.h"
4
#include "attitude.h"
5
#include "dongfangMath.h"
5
#include "dongfangMath.h"
6
#include "commands.h"
6
#include "commands.h"
7
 
7
 
8
// For scope debugging only!
8
// For scope debugging only!
9
#include "rc.h"
9
#include "rc.h"
10
 
10
 
11
// where our main data flow comes from.
11
// where our main data flow comes from.
12
#include "analog.h"
12
#include "analog.h"
13
 
13
 
14
#include "configuration.h"
14
#include "configuration.h"
15
#include "output.h"
15
#include "output.h"
16
 
16
 
17
// Some calculations are performed depending on some stick related things.
17
// Some calculations are performed depending on some stick related things.
18
#include "controlMixer.h"
18
#include "controlMixer.h"
19
 
19
 
20
#define CHECK_MIN_MAX(value, min, max) {if(value < min) value = min; else if(value > max) value = max;}
20
#define CHECK_MIN_MAX(value, min, max) {if(value < min) value = min; else if(value > max) value = max;}
21
 
21
 
22
/*
22
/*
23
 * Gyro readings, as read from the analog module. It would have been nice to flow
23
 * Gyro readings, as read from the analog module. It would have been nice to flow
24
 * them around between the different calculations as a struct or array (doing
24
 * them around between the different calculations as a struct or array (doing
25
 * things functionally without side effects) but this is shorter and probably
25
 * things functionally without side effects) but this is shorter and probably
26
 * faster too.
26
 * faster too.
27
 * The variables are overwritten at each attitude calculation invocation - the values
27
 * The variables are overwritten at each attitude calculation invocation - the values
28
 * are not preserved or reused.
28
 * are not preserved or reused.
29
 */
29
 */
30
int16_t rate_ATT[2], yawRate;
30
int16_t rate_ATT[2], yawRate;
31
 
31
 
32
// With different (less) filtering
32
// With different (less) filtering
33
int16_t rate_PID[2];
33
int16_t rate_PID[2];
34
int16_t differential[2];
34
int16_t differential[2];
35
 
35
 
36
/*
36
/*
37
 * Gyro readings, after performing "axis coupling" - that is, the transfomation
37
 * Gyro readings, after performing "axis coupling" - that is, the transfomation
38
 * of rotation rates from the airframe-local coordinate system to a ground-fixed
38
 * of rotation rates from the airframe-local coordinate system to a ground-fixed
39
 * coordinate system. If axis copling is disabled, the gyro readings will be
39
 * coordinate system. If axis copling is disabled, the gyro readings will be
40
 * copied into these directly.
40
 * copied into these directly.
41
 * These are global for the same pragmatic reason as with the gyro readings.
41
 * These are global for the same pragmatic reason as with the gyro readings.
42
 * The variables are overwritten at each attitude calculation invocation - the values
42
 * The variables are overwritten at each attitude calculation invocation - the values
43
 * are not preserved or reused.
43
 * are not preserved or reused.
44
 */
44
 */
45
int16_t ACRate[2], ACYawRate;
45
int16_t ACRate[2], ACYawRate;
46
 
46
 
47
/*
47
/*
48
 * Gyro integrals. These are the rotation angles of the airframe compared to the
48
 * Gyro integrals. These are the rotation angles of the airframe compared to the
49
 * horizontal plane, yaw relative to yaw at start.
49
 * horizontal plane, yaw relative to yaw at start.
50
 */
50
 */
51
int32_t attitude[2];
51
int32_t attitude[2];
52
 
52
 
53
//int readingHeight = 0;
53
//int readingHeight = 0;
54
 
54
 
55
// Yaw angle and compass stuff.
55
// Yaw angle and compass stuff.
56
int32_t headingError;
56
int32_t headingError;
57
 
57
 
58
// The difference between the above 2 (heading - course) on a -180..179 degree interval.
58
// The difference between the above 2 (heading - course) on a -180..179 degree interval.
59
// Not necessary. Never read anywhere.
59
// Not necessary. Never read anywhere.
60
// int16_t compassOffCourse = 0;
60
// int16_t compassOffCourse = 0;
61
 
61
 
62
uint16_t ignoreCompassTimer = 0;// 500;
62
uint16_t ignoreCompassTimer = 0;// 500;
63
 
63
 
64
int32_t heading; // Yaw Gyro Integral supported by compass
64
int32_t heading; // Yaw Gyro Integral supported by compass
65
int16_t yawGyroDrift;
65
int16_t yawGyroDrift;
66
 
66
 
67
int16_t correctionSum[2] = { 0, 0 };
67
int16_t correctionSum[2] = { 0, 0 };
68
 
68
 
69
// For NaviCTRL use.
69
// For NaviCTRL use.
70
int16_t averageAcc[2] = { 0, 0 }, averageAccCount = 0;
70
int16_t averageAcc[2] = { 0, 0 }, averageAccCount = 0;
71
 
71
 
72
/*
72
/*
73
 * Experiment: Compensating for dynamic-induced gyro biasing.
73
 * Experiment: Compensating for dynamic-induced gyro biasing.
74
 */
74
 */
75
int16_t driftComp[2] = { 0, 0 }, driftCompYaw = 0;
75
int16_t driftComp[2] = { 0, 0 }, driftCompYaw = 0;
76
// int16_t savedDynamicOffsetPitch = 0, savedDynamicOffsetRoll = 0;
76
// int16_t savedDynamicOffsetPitch = 0, savedDynamicOffsetRoll = 0;
77
// int32_t dynamicCalPitch, dynamicCalRoll, dynamicCalYaw;
77
// int32_t dynamicCalPitch, dynamicCalRoll, dynamicCalYaw;
78
// int16_t dynamicCalCount;
78
// int16_t dynamicCalCount;
79
 
79
 
80
uint16_t accVector;
80
uint16_t accVector;
81
 
81
 
82
/************************************************************************
82
/************************************************************************
83
 * Set inclination angles from the acc. sensor data.                    
83
 * Set inclination angles from the acc. sensor data.                    
84
 * If acc. sensors are not used, set to zero.                          
84
 * If acc. sensors are not used, set to zero.                          
85
 * TODO: One could use inverse sine to calculate the angles more        
85
 * TODO: One could use inverse sine to calculate the angles more        
86
 * accurately, but since: 1) the angles are rather small at times when
86
 * accurately, but since: 1) the angles are rather small at times when
87
 * it makes sense to set the integrals (standing on ground, or flying at  
87
 * it makes sense to set the integrals (standing on ground, or flying at  
88
 * constant speed, and 2) at small angles a, sin(a) ~= constant * a,    
88
 * constant speed, and 2) at small angles a, sin(a) ~= constant * a,    
89
 * it is hardly worth the trouble.                                      
89
 * it is hardly worth the trouble.                                      
90
 ************************************************************************/
90
 ************************************************************************/
91
 
91
 
92
int32_t getAngleEstimateFromAcc(uint8_t axis) {
92
int32_t getAngleEstimateFromAcc(uint8_t axis) {
93
  //int32_t correctionTerm = (dynamicParams.levelCorrection[axis] - 128) * 256L;
93
  //int32_t correctionTerm = (dynamicParams.levelCorrection[axis] - 128) * 256L;
94
  return (int32_t) GYRO_ACC_FACTOR * (int32_t) filteredAcc[axis]; // + correctionTerm;
94
  return (int32_t) GYRO_ACC_FACTOR * (int32_t) filteredAcc[axis]; // + correctionTerm;
95
  // return 342L * filteredAcc[axis];
95
  // return 342L * filteredAcc[axis];
96
}
96
}
97
 
97
 
98
void setStaticAttitudeAngles(void) {
98
void setStaticAttitudeAngles(void) {
99
#ifdef ATTITUDE_USE_ACC_SENSORS
99
#ifdef ATTITUDE_USE_ACC_SENSORS
100
  attitude[PITCH] = getAngleEstimateFromAcc(PITCH);
100
  attitude[PITCH] = getAngleEstimateFromAcc(PITCH);
101
  attitude[ROLL] = getAngleEstimateFromAcc(ROLL);
101
  attitude[ROLL] = getAngleEstimateFromAcc(ROLL);
102
#else
102
#else
103
  attitude[PITCH] = attitude[ROLL] = 0;
103
  attitude[PITCH] = attitude[ROLL] = 0;
104
#endif
104
#endif
105
}
105
}
106
 
106
 
107
/************************************************************************
107
/************************************************************************
108
 * Neutral Readings                                                    
108
 * Neutral Readings                                                    
109
 ************************************************************************/
109
 ************************************************************************/
110
void attitude_setNeutral(void) {
110
void attitude_setNeutral(void) {
111
  // Servo_Off(); // disable servo output. TODO: Why bother? The servos are going to make a jerk anyway.
111
  // Servo_Off(); // disable servo output. TODO: Why bother? The servos are going to make a jerk anyway.
112
  // dynamicParams.axisCoupling1 = dynamicParams.axisCoupling2 = 0;
112
  // dynamicParams.axisCoupling1 = dynamicParams.axisCoupling2 = 0;
113
 
113
 
114
  driftComp[PITCH] = driftComp[ROLL] = yawGyroDrift = driftCompYaw = 0;
114
  driftComp[PITCH] = driftComp[ROLL] = yawGyroDrift = driftCompYaw = 0;
115
  correctionSum[PITCH] = correctionSum[ROLL] = 0;
115
  correctionSum[PITCH] = correctionSum[ROLL] = 0;
116
 
116
 
117
  // Calibrate hardware.
117
  // Calibrate hardware.
118
  analog_setNeutral();
118
  analog_setNeutral();
119
 
119
 
120
  // reset gyro integrals to acc guessing
120
  // reset gyro integrals to acc guessing
121
  setStaticAttitudeAngles();
121
  setStaticAttitudeAngles();
-
 
122
#ifdef USE_MK3MAG
122
  attitude_resetHeadingToMagnetic();
123
  attitude_resetHeadingToMagnetic();
-
 
124
#endif
123
  // Servo_On(); //enable servo output
125
  // Servo_On(); //enable servo output
124
}
126
}
125
 
127
 
126
/************************************************************************
128
/************************************************************************
127
 * Get sensor data from the analog module, and release the ADC          
129
 * Get sensor data from the analog module, and release the ADC          
128
 * TODO: Ultimately, the analog module could do this (instead of dumping
130
 * TODO: Ultimately, the analog module could do this (instead of dumping
129
 * the values into variables).
131
 * the values into variables).
130
 * The rate variable end up in a range of about [-1024, 1023].
132
 * The rate variable end up in a range of about [-1024, 1023].
131
 *************************************************************************/
133
 *************************************************************************/
132
void getAnalogData(void) {
134
void getAnalogData(void) {
133
  uint8_t axis;
135
  uint8_t axis;
134
 
136
 
135
  analog_update();
137
  analog_update();
136
 
138
 
137
  for (axis = PITCH; axis <= ROLL; axis++) {
139
  for (axis = PITCH; axis <= ROLL; axis++) {
138
    rate_PID[axis] = gyro_PID[axis] + driftComp[axis];
140
    rate_PID[axis] = gyro_PID[axis] + driftComp[axis];
139
    rate_ATT[axis] = gyro_ATT[axis] + driftComp[axis];
141
    rate_ATT[axis] = gyro_ATT[axis] + driftComp[axis];
140
    differential[axis] = gyroD[axis];
142
    differential[axis] = gyroD[axis];
141
    averageAcc[axis] += acc[axis];
143
    averageAcc[axis] += acc[axis];
142
  }
144
  }
143
 
145
 
144
  averageAccCount++;
146
  averageAccCount++;
145
  yawRate = yawGyro + driftCompYaw;
147
  yawRate = yawGyro + driftCompYaw;
146
}
148
}
147
 
149
 
148
/*
150
/*
149
 * This is the standard flight-style coordinate system transformation
151
 * This is the standard flight-style coordinate system transformation
150
 * (from airframe-local axes to a ground-based system). For some reason
152
 * (from airframe-local axes to a ground-based system). For some reason
151
 * the MK uses a left-hand coordinate system. The tranformation has been
153
 * the MK uses a left-hand coordinate system. The tranformation has been
152
 * changed accordingly.
154
 * changed accordingly.
153
 */
155
 */
154
void trigAxisCoupling(void) {
156
void trigAxisCoupling(void) {
155
  int16_t rollAngleInDegrees = attitude[ROLL] / GYRO_DEG_FACTOR_PITCHROLL;
157
  int16_t rollAngleInDegrees = attitude[ROLL] / GYRO_DEG_FACTOR_PITCHROLL;
156
  int16_t pitchAngleInDegrees = attitude[PITCH] / GYRO_DEG_FACTOR_PITCHROLL;
158
  int16_t pitchAngleInDegrees = attitude[PITCH] / GYRO_DEG_FACTOR_PITCHROLL;
157
 
159
 
158
  int16_t cospitch = cos_360(pitchAngleInDegrees);
160
  int16_t cospitch = cos_360(pitchAngleInDegrees);
159
  int16_t cosroll = cos_360(rollAngleInDegrees);
161
  int16_t cosroll = cos_360(rollAngleInDegrees);
160
  int16_t sinroll = sin_360(rollAngleInDegrees);
162
  int16_t sinroll = sin_360(rollAngleInDegrees);
161
 
163
 
162
  ACRate[PITCH] = (((int32_t) rate_ATT[PITCH] * cosroll
164
  ACRate[PITCH] = (((int32_t) rate_ATT[PITCH] * cosroll
163
      - (int32_t) yawRate * sinroll) >> LOG_MATH_UNIT_FACTOR);
165
      - (int32_t) yawRate * sinroll) >> LOG_MATH_UNIT_FACTOR);
164
 
166
 
165
  ACRate[ROLL] = rate_ATT[ROLL]
167
  ACRate[ROLL] = rate_ATT[ROLL]
166
      + (((((int32_t) rate_ATT[PITCH] * sinroll + (int32_t) yawRate * cosroll)
168
      + (((((int32_t) rate_ATT[PITCH] * sinroll + (int32_t) yawRate * cosroll)
167
          >> LOG_MATH_UNIT_FACTOR) * tan_360(pitchAngleInDegrees))
169
          >> LOG_MATH_UNIT_FACTOR) * tan_360(pitchAngleInDegrees))
168
          >> LOG_MATH_UNIT_FACTOR);
170
          >> LOG_MATH_UNIT_FACTOR);
169
 
171
 
170
  ACYawRate =
172
  ACYawRate =
171
      ((int32_t) rate_ATT[PITCH] * sinroll + (int32_t) yawRate * cosroll)
173
      ((int32_t) rate_ATT[PITCH] * sinroll + (int32_t) yawRate * cosroll)
172
          / cospitch;
174
          / cospitch;
173
 
175
 
174
  ACYawRate =
176
  ACYawRate =
175
      ((int32_t) rate_ATT[PITCH] * sinroll + (int32_t) yawRate * cosroll)
177
      ((int32_t) rate_ATT[PITCH] * sinroll + (int32_t) yawRate * cosroll)
176
          / cospitch;
178
          / cospitch;
177
}
179
}
178
 
180
 
179
// 480 usec with axis coupling - almost no time without.
181
// 480 usec with axis coupling - almost no time without.
180
void integrate(void) {
182
void integrate(void) {
181
  // First, perform axis coupling. If disabled xxxRate is just copied to ACxxxRate.
183
  // First, perform axis coupling. If disabled xxxRate is just copied to ACxxxRate.
182
  uint8_t axis;
184
  uint8_t axis;
183
 
185
 
184
  if (staticParams.bitConfig & CFG_AXIS_COUPLING_ACTIVE) {
186
  if (staticParams.bitConfig & CFG_AXIS_COUPLING_ACTIVE) {
185
    trigAxisCoupling();
187
    trigAxisCoupling();
186
  } else {
188
  } else {
187
    ACRate[PITCH] = rate_ATT[PITCH];
189
    ACRate[PITCH] = rate_ATT[PITCH];
188
    ACRate[ROLL] = rate_ATT[ROLL];
190
    ACRate[ROLL] = rate_ATT[ROLL];
189
    ACYawRate = yawRate;
191
    ACYawRate = yawRate;
190
  }
192
  }
191
 
193
 
192
  /*
194
  /*
193
   * Yaw
195
   * Yaw
194
   * Calculate yaw gyro integral (~ to rotation angle)
196
   * Calculate yaw gyro integral (~ to rotation angle)
195
   * Limit heading proportional to 0 deg to 360 deg
197
   * Limit heading proportional to 0 deg to 360 deg
196
   */
198
   */
197
  heading += ACYawRate;
199
  heading += ACYawRate;
198
  intervalWrap(&heading, YAWOVER360);
200
  intervalWrap(&heading, YAWOVER360);
199
 
201
 
200
  headingError += ACYawRate;
202
  headingError += ACYawRate;
201
 
203
 
202
  debugOut.analog[27] = heading / 100;
204
  debugOut.analog[27] = heading / 100;
203
 
205
 
204
  /*
206
  /*
205
   * Pitch axis integration and range boundary wrap.
207
   * Pitch axis integration and range boundary wrap.
206
   */
208
   */
207
  for (axis = PITCH; axis <= ROLL; axis++) {
209
  for (axis = PITCH; axis <= ROLL; axis++) {
208
    attitude[axis] += ACRate[axis];
210
    attitude[axis] += ACRate[axis];
209
    if (attitude[axis] > PITCHROLLOVER180) {
211
    if (attitude[axis] > PITCHROLLOVER180) {
210
      attitude[axis] -= PITCHROLLOVER360;
212
      attitude[axis] -= PITCHROLLOVER360;
211
    } else if (attitude[axis] <= -PITCHROLLOVER180) {
213
    } else if (attitude[axis] <= -PITCHROLLOVER180) {
212
      attitude[axis] += PITCHROLLOVER360;
214
      attitude[axis] += PITCHROLLOVER360;
213
    }
215
    }
214
  }
216
  }
215
}
217
}
216
 
218
 
217
/************************************************************************
219
/************************************************************************
218
 * A kind of 0'th order integral correction, that corrects the integrals
220
 * A kind of 0'th order integral correction, that corrects the integrals
219
 * directly. This is the "gyroAccFactor" stuff in the original code.
221
 * directly. This is the "gyroAccFactor" stuff in the original code.
220
 * There is (there) also a drift compensation
222
 * There is (there) also a drift compensation
221
 * - it corrects the differential of the integral = the gyro offsets.
223
 * - it corrects the differential of the integral = the gyro offsets.
222
 * That should only be necessary with drifty gyros like ENC-03.
224
 * That should only be necessary with drifty gyros like ENC-03.
223
 ************************************************************************/
225
 ************************************************************************/
224
void correctIntegralsByAcc0thOrder(void) {
226
void correctIntegralsByAcc0thOrder(void) {
225
  // TODO: Consider changing this to: Only correct when integrals are less than ...., or only correct when angular velocities
227
  // TODO: Consider changing this to: Only correct when integrals are less than ...., or only correct when angular velocities
226
  // are less than ....., or reintroduce Kalman.
228
  // are less than ....., or reintroduce Kalman.
227
  // Well actually the Z axis acc. check is not so silly.
229
  // Well actually the Z axis acc. check is not so silly.
228
  uint8_t axis;
230
  uint8_t axis;
229
  int32_t temp;
231
  int32_t temp;
230
 
232
 
231
  uint8_t ca = controlActivity >> 8;
233
  uint8_t ca = controlActivity >> 8;
232
  uint8_t highControlActivity = (ca > staticParams.maxControlActivity);
234
  uint8_t highControlActivity = (ca > staticParams.maxControlActivity);
233
 
235
 
234
  if (highControlActivity) {
236
  if (highControlActivity) {
235
    debugOut.digital[1] |= DEBUG_ACC0THORDER;
237
    debugOut.digital[1] |= DEBUG_ACC0THORDER;
236
  } else {
238
  } else {
237
    debugOut.digital[1] &= ~DEBUG_ACC0THORDER;
239
    debugOut.digital[1] &= ~DEBUG_ACC0THORDER;
238
  }
240
  }
239
 
241
 
240
  if (accVector <= dynamicParams.maxAccVector) {
242
  if (accVector <= dynamicParams.maxAccVector) {
241
    debugOut.digital[0] &= ~DEBUG_ACC0THORDER;
243
    debugOut.digital[0] &= ~DEBUG_ACC0THORDER;
242
 
244
 
243
    uint8_t permilleAcc = staticParams.zerothOrderCorrection;
245
    uint8_t permilleAcc = staticParams.zerothOrderCorrection;
244
    int32_t accDerived;
246
    int32_t accDerived;
245
 
247
 
246
    /*
248
    /*
247
     if ((controlYaw < -64) || (controlYaw > 64)) { // reduce further if yaw stick is active
249
     if ((controlYaw < -64) || (controlYaw > 64)) { // reduce further if yaw stick is active
248
     permilleAcc /= 2;
250
     permilleAcc /= 2;
249
     debugFullWeight = 0;
251
     debugFullWeight = 0;
250
     }
252
     }
251
 
253
 
252
     if ((maxControl[PITCH] > 64) || (maxControl[ROLL] > 64)) { // reduce effect during stick commands. Replace by controlActivity.
254
     if ((maxControl[PITCH] > 64) || (maxControl[ROLL] > 64)) { // reduce effect during stick commands. Replace by controlActivity.
253
     permilleAcc /= 2;
255
     permilleAcc /= 2;
254
     debugFullWeight = 0;
256
     debugFullWeight = 0;
255
     */
257
     */
256
 
258
 
257
    if (highControlActivity) { // reduce effect during stick control activity
259
    if (highControlActivity) { // reduce effect during stick control activity
258
      permilleAcc /= 4;
260
      permilleAcc /= 4;
259
      if (controlActivity > staticParams.maxControlActivity * 2) { // reduce effect during stick control activity
261
      if (controlActivity > staticParams.maxControlActivity * 2) { // reduce effect during stick control activity
260
        permilleAcc /= 4;
262
        permilleAcc /= 4;
261
      }
263
      }
262
    }
264
    }
263
 
265
 
264
    /*
266
    /*
265
     * Add to each sum: The amount by which the angle is changed just below.
267
     * Add to each sum: The amount by which the angle is changed just below.
266
     */
268
     */
267
    for (axis = PITCH; axis <= ROLL; axis++) {
269
    for (axis = PITCH; axis <= ROLL; axis++) {
268
      accDerived = getAngleEstimateFromAcc(axis);
270
      accDerived = getAngleEstimateFromAcc(axis);
269
      debugOut.analog[9 + axis] = accDerived / (GYRO_DEG_FACTOR_PITCHROLL / 10);
271
      debugOut.analog[9 + axis] = accDerived / (GYRO_DEG_FACTOR_PITCHROLL / 10);
270
      // 1000 * the correction amount that will be added to the gyro angle in next line.
272
      // 1000 * the correction amount that will be added to the gyro angle in next line.
271
      temp = attitude[axis];
273
      temp = attitude[axis];
272
      attitude[axis] = ((int32_t) (1000L - permilleAcc) * temp
274
      attitude[axis] = ((int32_t) (1000L - permilleAcc) * temp
273
          + (int32_t) permilleAcc * accDerived) / 1000L;
275
          + (int32_t) permilleAcc * accDerived) / 1000L;
274
      correctionSum[axis] += attitude[axis] - temp;
276
      correctionSum[axis] += attitude[axis] - temp;
275
    }
277
    }
276
  } else {
278
  } else {
277
    debugOut.analog[9] = 0;
279
    debugOut.analog[9] = 0;
278
    debugOut.analog[10] = 0;
280
    debugOut.analog[10] = 0;
279
    // experiment: Kill drift compensation updates when not flying smooth.
281
    // experiment: Kill drift compensation updates when not flying smooth.
280
    // correctionSum[PITCH] = correctionSum[ROLL] = 0;
282
    // correctionSum[PITCH] = correctionSum[ROLL] = 0;
281
    debugOut.digital[0] |= DEBUG_ACC0THORDER;
283
    debugOut.digital[0] |= DEBUG_ACC0THORDER;
282
  }
284
  }
283
}
285
}
284
 
286
 
285
/************************************************************************
287
/************************************************************************
286
 * This is an attempt to correct not the error in the angle integrals
288
 * This is an attempt to correct not the error in the angle integrals
287
 * (that happens in correctIntegralsByAcc0thOrder above) but rather the
289
 * (that happens in correctIntegralsByAcc0thOrder above) but rather the
288
 * cause of it: Gyro drift, vibration and rounding errors.
290
 * cause of it: Gyro drift, vibration and rounding errors.
289
 * All the corrections made in correctIntegralsByAcc0thOrder over
291
 * All the corrections made in correctIntegralsByAcc0thOrder over
290
 * DRIFTCORRECTION_TIME cycles are summed up. This number is
292
 * DRIFTCORRECTION_TIME cycles are summed up. This number is
291
 * then divided by DRIFTCORRECTION_TIME to get the approx.
293
 * then divided by DRIFTCORRECTION_TIME to get the approx.
292
 * correction that should have been applied to each iteration to fix
294
 * correction that should have been applied to each iteration to fix
293
 * the error. This is then added to the dynamic offsets.
295
 * the error. This is then added to the dynamic offsets.
294
 ************************************************************************/
296
 ************************************************************************/
295
// 2 times / sec. = 488/2
297
// 2 times / sec. = 488/2
296
#define DRIFTCORRECTION_TIME 256L
298
#define DRIFTCORRECTION_TIME 256L
297
void driftCorrection(void) {
299
void driftCorrection(void) {
298
  static int16_t timer = DRIFTCORRECTION_TIME;
300
  static int16_t timer = DRIFTCORRECTION_TIME;
299
  int16_t deltaCorrection;
301
  int16_t deltaCorrection;
300
  int16_t round;
302
  int16_t round;
301
  uint8_t axis;
303
  uint8_t axis;
302
 
304
 
303
  if (!--timer) {
305
  if (!--timer) {
304
    timer = DRIFTCORRECTION_TIME;
306
    timer = DRIFTCORRECTION_TIME;
305
    for (axis = PITCH; axis <= ROLL; axis++) {
307
    for (axis = PITCH; axis <= ROLL; axis++) {
306
      // Take the sum of corrections applied, add it to delta
308
      // Take the sum of corrections applied, add it to delta
307
      if (correctionSum[axis] >= 0)
309
      if (correctionSum[axis] >= 0)
308
        round = DRIFTCORRECTION_TIME / 2;
310
        round = DRIFTCORRECTION_TIME / 2;
309
      else
311
      else
310
        round = -DRIFTCORRECTION_TIME / 2;
312
        round = -DRIFTCORRECTION_TIME / 2;
311
      deltaCorrection = (correctionSum[axis] + round) / DRIFTCORRECTION_TIME;
313
      deltaCorrection = (correctionSum[axis] + round) / DRIFTCORRECTION_TIME;
312
      // Add the delta to the compensation. So positive delta means, gyro should have higher value.
314
      // Add the delta to the compensation. So positive delta means, gyro should have higher value.
313
      driftComp[axis] += deltaCorrection / staticParams.driftCompDivider;
315
      driftComp[axis] += deltaCorrection / staticParams.driftCompDivider;
314
      CHECK_MIN_MAX(driftComp[axis], -staticParams.driftCompLimit, staticParams.driftCompLimit);
316
      CHECK_MIN_MAX(driftComp[axis], -staticParams.driftCompLimit, staticParams.driftCompLimit);
315
      // DebugOut.Analog[11 + axis] = correctionSum[axis];
317
      // DebugOut.Analog[11 + axis] = correctionSum[axis];
316
      // DebugOut.Analog[16 + axis] = correctionSum[axis];
318
      // DebugOut.Analog[16 + axis] = correctionSum[axis];
317
      // debugOut.analog[28 + axis] = driftComp[axis];
319
      // debugOut.analog[28 + axis] = driftComp[axis];
318
      correctionSum[axis] = 0;
320
      correctionSum[axis] = 0;
319
    }
321
    }
320
  }
322
  }
321
}
323
}
322
 
324
 
323
void calculateAccVector(void) {
325
void calculateAccVector(void) {
324
  int16_t temp;
326
  int16_t temp;
325
  temp = filteredAcc[0] >> 3;
327
  temp = filteredAcc[0] >> 3;
326
  accVector = temp * temp;
328
  accVector = temp * temp;
327
  temp = filteredAcc[1] >> 3;
329
  temp = filteredAcc[1] >> 3;
328
  accVector += temp * temp;
330
  accVector += temp * temp;
329
  temp = filteredAcc[2] >> 3;
331
  temp = filteredAcc[2] >> 3;
330
  accVector += temp * temp;
332
  accVector += temp * temp;
331
  //debugOut.analog[18] = accVector;
333
  //debugOut.analog[18] = accVector;
332
}
334
}
-
 
335
 
333
 
336
#ifdef USE_MK3MAG
334
void attitude_resetHeadingToMagnetic(void) {
337
void attitude_resetHeadingToMagnetic(void) {
335
  if (commands_isCalibratingCompass())
338
  if (commands_isCalibratingCompass())
336
    return;
339
    return;
337
 
340
 
338
  // Compass is off, skip.
341
  // Compass is off, skip.
339
  if (!(staticParams.bitConfig & CFG_COMPASS_ACTIVE))
342
  if (!(staticParams.bitConfig & CFG_COMPASS_ENABLED))
340
      return;
343
      return;
341
 
344
 
342
  // Compass is invalid, skip.
345
  // Compass is invalid, skip.
343
  if (magneticHeading < 0)
346
  if (magneticHeading < 0)
344
    return;
347
    return;
345
 
348
 
346
  heading = (int32_t) magneticHeading * GYRO_DEG_FACTOR_YAW;
349
  heading = (int32_t) magneticHeading * GYRO_DEG_FACTOR_YAW;
347
  //targetHeading = heading;
350
  //targetHeading = heading;
348
  headingError = 0;
351
  headingError = 0;
349
 
352
 
350
  debugOut.digital[0] ^= DEBUG_COMPASS;
353
  debugOut.digital[0] ^= DEBUG_COMPASS;
351
}
354
}
352
 
355
 
353
void correctHeadingToMagnetic(void) {
356
void correctHeadingToMagnetic(void) {
354
  int32_t error;
357
  int32_t error;
355
 
358
 
356
  if (commands_isCalibratingCompass()) {
359
  if (commands_isCalibratingCompass()) {
357
    debugOut.analog[29] = 1;
360
    debugOut.analog[29] = 1;
358
    return;
361
    return;
359
  }
362
  }
360
 
363
 
361
  // Compass is off, skip.
364
  // Compass is off, skip.
362
  // Naaah this is assumed.
365
  // Naaah this is assumed.
363
  // if (!(staticParams.bitConfig & CFG_COMPASS_ACTIVE))
366
  // if (!(staticParams.bitConfig & CFG_COMPASS_ACTIVE))
364
  //     return;
367
  //     return;
365
 
368
 
366
  // Compass is invalid, skip.
369
  // Compass is invalid, skip.
367
  if (magneticHeading < 0) {
370
  if (magneticHeading < 0) {
368
    debugOut.analog[29] = 2;
371
    debugOut.analog[29] = 2;
369
    return;
372
    return;
370
  }
373
  }
371
 
374
 
372
  // Spinning fast, skip
375
  // Spinning fast, skip
373
  if (abs(yawRate) > 128) {
376
  if (abs(yawRate) > 128) {
374
    debugOut.analog[29] = 3;
377
    debugOut.analog[29] = 3;
375
    return;
378
    return;
376
  }
379
  }
377
 
380
 
378
  // Otherwise invalidated, skip
381
  // Otherwise invalidated, skip
379
  if (ignoreCompassTimer) {
382
  if (ignoreCompassTimer) {
380
    ignoreCompassTimer--;
383
    ignoreCompassTimer--;
381
    debugOut.analog[29] = 4;
384
    debugOut.analog[29] = 4;
382
    return;
385
    return;
383
  }
386
  }
384
 
387
 
385
  // TODO: Find computational cost of this.
388
  // TODO: Find computational cost of this.
386
  error = ((int32_t)magneticHeading*GYRO_DEG_FACTOR_YAW - heading);
389
  error = ((int32_t)magneticHeading*GYRO_DEG_FACTOR_YAW - heading);
387
  if (error <= -YAWOVER180) error += YAWOVER360;
390
  if (error <= -YAWOVER180) error += YAWOVER360;
388
  else if (error > YAWOVER180) error -= YAWOVER360;
391
  else if (error > YAWOVER180) error -= YAWOVER360;
389
 
392
 
390
  // We only correct errors larger than the resolution of the compass, or else we would keep rounding the
393
  // We only correct errors larger than the resolution of the compass, or else we would keep rounding the
391
  // better resolution of the gyros to the worse resolution of the compass all the time.
394
  // better resolution of the gyros to the worse resolution of the compass all the time.
392
  // The correction should really only serve to compensate for gyro drift.
395
  // The correction should really only serve to compensate for gyro drift.
393
  if(abs(error) < GYRO_DEG_FACTOR_YAW) return;
396
  if(abs(error) < GYRO_DEG_FACTOR_YAW) return;
394
 
397
 
395
  int32_t correction = (error * staticParams.compassYawCorrection) >> 8;
398
  int32_t correction = (error * staticParams.compassYawCorrection) >> 8;
396
  debugOut.analog[30] = correction;
399
  debugOut.analog[30] = correction;
397
 
400
 
398
  // The correction is added both to current heading (the direction in which the copter thinks it is pointing)
401
  // The correction is added both to current heading (the direction in which the copter thinks it is pointing)
399
  // and to the target heading (the direction to which it maneuvers to point). That means, this correction has
402
  // and to the target heading (the direction to which it maneuvers to point). That means, this correction has
400
  // no effect on control at all!!! It only has effect on the values of the two variables. However, these values
403
  // no effect on control at all!!! It only has effect on the values of the two variables. However, these values
401
  // could have effect on control elsewhere, like in compassControl.c .
404
  // could have effect on control elsewhere, like in compassControl.c .
402
  heading += correction;
405
  heading += correction;
403
  intervalWrap(&heading, YAWOVER360);
406
  intervalWrap(&heading, YAWOVER360);
404
 
407
 
405
  // If we want a transparent flight wrt. compass correction (meaning the copter does not change attitude all
408
  // If we want a transparent flight wrt. compass correction (meaning the copter does not change attitude all
406
  // when the compass corrects the heading - it only corrects numbers!) we want to add:
409
  // when the compass corrects the heading - it only corrects numbers!) we want to add:
407
  // This will however cause drift to remain uncorrected!
410
  // This will however cause drift to remain uncorrected!
408
  // headingError += correction;
411
  // headingError += correction;
409
  debugOut.analog[29] = 0;
412
  debugOut.analog[29] = 0;
410
}
413
}
-
 
414
#endif
411
 
415
 
412
/************************************************************************
416
/************************************************************************
413
 * Main procedure.
417
 * Main procedure.
414
 ************************************************************************/
418
 ************************************************************************/
415
void calculateFlightAttitude(void) {
419
void calculateFlightAttitude(void) {
416
  getAnalogData();
420
  getAnalogData();
417
  calculateAccVector();
421
  calculateAccVector();
418
  integrate();
422
  integrate();
419
 
423
 
420
#ifdef ATTITUDE_USE_ACC_SENSORS
424
#ifdef ATTITUDE_USE_ACC_SENSORS
421
  correctIntegralsByAcc0thOrder();
425
  correctIntegralsByAcc0thOrder();
422
  driftCorrection();
426
  driftCorrection();
423
#endif
427
#endif
424
 
428
 
425
  // We are done reading variables from the analog module.
429
  // We are done reading variables from the analog module.
426
  // Interrupt-driven sensor reading may restart.
430
  // Interrupt-driven sensor reading may restart.
427
  startAnalogConversionCycle();
431
  startAnalogConversionCycle();
-
 
432
 
428
 
433
#ifdef USE_MK3MAG
429
  if (staticParams.bitConfig & (CFG_COMPASS_ACTIVE | CFG_GPS_ACTIVE)) {
434
  if (staticParams.bitConfig & (CFG_COMPASS_ENABLED | CFG_GPS_ENABLED)) {
430
    correctHeadingToMagnetic();
435
    correctHeadingToMagnetic();
-
 
436
  }
431
  }
437
#endif
432
}
438
}
433
 
439
 
434
/*
440
/*
435
 * This is part of an experiment to measure average sensor offsets caused by motor vibration,
441
 * This is part of an experiment to measure average sensor offsets caused by motor vibration,
436
 * and to compensate them away. It brings about some improvement, but no miracles.
442
 * and to compensate them away. It brings about some improvement, but no miracles.
437
 * As long as the left stick is kept in the start-motors position, the dynamic compensation
443
 * As long as the left stick is kept in the start-motors position, the dynamic compensation
438
 * will measure the effect of vibration, to use for later compensation. So, one should keep
444
 * will measure the effect of vibration, to use for later compensation. So, one should keep
439
 * the stick in the start-motors position for a few seconds, till all motors run (at the wrong
445
 * the stick in the start-motors position for a few seconds, till all motors run (at the wrong
440
 * speed unfortunately... must find a better way)
446
 * speed unfortunately... must find a better way)
441
 */
447
 */
442
/*
448
/*
443
 void attitude_startDynamicCalibration(void) {
449
 void attitude_startDynamicCalibration(void) {
444
 dynamicCalPitch = dynamicCalRoll = dynamicCalYaw = dynamicCalCount = 0;
450
 dynamicCalPitch = dynamicCalRoll = dynamicCalYaw = dynamicCalCount = 0;
445
 savedDynamicOffsetPitch = savedDynamicOffsetRoll = 1000;
451
 savedDynamicOffsetPitch = savedDynamicOffsetRoll = 1000;
446
 }
452
 }
447
 
453
 
448
 void attitude_continueDynamicCalibration(void) {
454
 void attitude_continueDynamicCalibration(void) {
449
 // measure dynamic offset now...
455
 // measure dynamic offset now...
450
 dynamicCalPitch += hiResPitchGyro;
456
 dynamicCalPitch += hiResPitchGyro;
451
 dynamicCalRoll += hiResRollGyro;
457
 dynamicCalRoll += hiResRollGyro;
452
 dynamicCalYaw += rawYawGyroSum;
458
 dynamicCalYaw += rawYawGyroSum;
453
 dynamicCalCount++;
459
 dynamicCalCount++;
454
 
460
 
455
 // Param6: Manual mode. The offsets are taken from Param7 and Param8.
461
 // Param6: Manual mode. The offsets are taken from Param7 and Param8.
456
 if (dynamicParams.UserParam6 || 1) { // currently always enabled.
462
 if (dynamicParams.UserParam6 || 1) { // currently always enabled.
457
 // manual mode
463
 // manual mode
458
 driftCompPitch = dynamicParams.UserParam7 - 128;
464
 driftCompPitch = dynamicParams.UserParam7 - 128;
459
 driftCompRoll = dynamicParams.UserParam8 - 128;
465
 driftCompRoll = dynamicParams.UserParam8 - 128;
460
 } else {
466
 } else {
461
 // use the sampled value (does not seem to work so well....)
467
 // use the sampled value (does not seem to work so well....)
462
 driftCompPitch = savedDynamicOffsetPitch = -dynamicCalPitch / dynamicCalCount;
468
 driftCompPitch = savedDynamicOffsetPitch = -dynamicCalPitch / dynamicCalCount;
463
 driftCompRoll = savedDynamicOffsetRoll = -dynamicCalRoll / dynamicCalCount;
469
 driftCompRoll = savedDynamicOffsetRoll = -dynamicCalRoll / dynamicCalCount;
464
 driftCompYaw = -dynamicCalYaw / dynamicCalCount;
470
 driftCompYaw = -dynamicCalYaw / dynamicCalCount;
465
 }
471
 }
466
 
472
 
467
 // keep resetting these meanwhile, to avoid accumulating errors.
473
 // keep resetting these meanwhile, to avoid accumulating errors.
468
 setStaticAttitudeIntegrals();
474
 setStaticAttitudeIntegrals();
469
 yawAngle = 0;
475
 yawAngle = 0;
470
 }
476
 }
471
 */
477
 */
472
 
478