Rev 1645 |
Blame |
Last modification |
View Log
| RSS feed
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Copyright (c) 04.2007 Holger Buss
// + Nur für den privaten Gebrauch
// + www.MikroKopter.com
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Es gilt für das gesamte Projekt (Hardware, Software, Binärfiles, Sourcecode und Dokumentation),
// + dass eine Nutzung (auch auszugsweise) nur für den privaten (nicht-kommerziellen) Gebrauch zulässig ist.
// + Sollten direkte oder indirekte kommerzielle Absichten verfolgt werden, ist mit uns (info@mikrokopter.de) Kontakt
// + bzgl. der Nutzungsbedingungen aufzunehmen.
// + Eine kommerzielle Nutzung ist z.B.Verkauf von MikroKoptern, Bestückung und Verkauf von Platinen oder Bausätzen,
// + Verkauf von Luftbildaufnahmen, usw.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Werden Teile des Quellcodes (mit oder ohne Modifikation) weiterverwendet oder veröffentlicht,
// + unterliegen sie auch diesen Nutzungsbedingungen und diese Nutzungsbedingungen incl. Copyright müssen dann beiliegen
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Sollte die Software (auch auszugesweise) oder sonstige Informationen des MikroKopter-Projekts
// + auf anderen Webseiten oder sonstigen Medien veröffentlicht werden, muss unsere Webseite "http://www.mikrokopter.de"
// + eindeutig als Ursprung verlinkt werden
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Keine Gewähr auf Fehlerfreiheit, Vollständigkeit oder Funktion
// + Benutzung auf eigene Gefahr
// + Wir übernehmen keinerlei Haftung für direkte oder indirekte Personen- oder Sachschäden
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Die Portierung der Software (oder Teile davon) auf andere Systeme (ausser der Hardware von www.mikrokopter.de) ist nur
// + mit unserer Zustimmung zulässig
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Die Funktion printf_P() unterliegt ihrer eigenen Lizenz und ist hiervon nicht betroffen
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Redistributions of source code (with or without modifications) must retain the above copyright notice,
// + this list of conditions and the following disclaimer.
// + * Neither the name of the copyright holders nor the names of contributors may be used to endorse or promote products derived
// + from this software without specific prior written permission.
// + * The use of this project (hardware, software, binary files, sources and documentation) is only permittet
// + for non-commercial use (directly or indirectly)
// + Commercial use (for excample: selling of MikroKopters, selling of PCBs, assembly, ...) is only permitted
// + with our written permission
// + * If sources or documentations are redistributet on other webpages, out webpage (http://www.MikroKopter.de) must be
// + clearly linked as origin
// + * porting to systems other than hardware from www.mikrokopter.de is not allowed
// + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN// + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// + POSSIBILITY OF SUCH DAMAGE.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/************************************************************************/
/* Flight Attitude */
/************************************************************************/
#include <stdlib.h>
#include <avr/io.h>
#include "attitude.h"
#include "dongfangMath.h"
// where our main data flow comes from.
#include "analog.h"
#include "configuration.h"
// Some calculations are performed depending on some stick related things.
#include "controlMixer.h"
// For Servo_On / Off
// #include "timer2.h"
#ifdef USE_MK3MAG
#include "mk3mag.h"
#include "gps.h"
#endif
#define CHECK_MIN_MAX(value, min, max) {if(value < min) value = min; else if(value > max) value = max;}
/*
* Gyro readings, as read from the analog module. It would have been nice to flow
* them around between the different calculations as a struct or array (doing
* things functionally without side effects) but this is shorter and probably
* faster too.
* The variables are overwritten at each attitude calculation invocation - the values
* are not preserved or reused.
*/
int16_t rate
[2], yawRate
;
// With different (less) filtering
int16_t rate_PID
[2];
int16_t differential
[2];
/*
* Gyro readings, after performing "axis coupling" - that is, the transfomation
* of rotation rates from the airframe-local coordinate system to a ground-fixed
* coordinate system. If axis copling is disabled, the gyro readings will be
* copied into these directly.
* These are global for the same pragmatic reason as with the gyro readings.
* The variables are overwritten at each attitude calculation invocation - the values
* are not preserved or reused.
*/
int16_t ACRate
[2], ACYawRate
;
/*
* Gyro integrals. These are the rotation angles of the airframe compared to the
* horizontal plane, yaw relative to yaw at start.
*/
int32_t angle
[2], yawAngle
;
int readingHeight
= 0;
// compass course
int16_t compassHeading
= -1; // negative angle indicates invalid data.
int16_t compassCourse
= -1;
int16_t compassOffCourse
= 0;
uint16_t updateCompassCourse
= 0;
uint8_t compassCalState
= 0;
// uint8_t FunnelCourse = 0;
uint16_t badCompassHeading
= 500;
int32_t yawGyroHeading
; // Yaw Gyro Integral supported by compass
#define PITCHROLLOVER180 (GYRO_DEG_FACTOR_PITCHROLL * 180L)
#define PITCHROLLOVER360 (GYRO_DEG_FACTOR_PITCHROLL * 360L)
#define YAWOVER360 (GYRO_DEG_FACTOR_YAW * 360L)
int16_t correctionSum
[2] = {0,0};
/*
* Experiment: Compensating for dynamic-induced gyro biasing.
*/
int16_t dynamicOffset
[2] = {0,0}, dynamicOffsetYaw
= 0;
// int16_t savedDynamicOffsetPitch = 0, savedDynamicOffsetRoll = 0;
// int32_t dynamicCalPitch, dynamicCalRoll, dynamicCalYaw;
// int16_t dynamicCalCount;
/************************************************************************
* Set inclination angles from the acc. sensor data.
* If acc. sensors are not used, set to zero.
* TODO: One could use inverse sine to calculate the angles more
* accurately, but since: 1) the angles are rather small at times when
* it makes sense to set the integrals (standing on ground, or flying at
* constant speed, and 2) at small angles a, sin(a) ~= constant * a,
* it is hardly worth the trouble.
************************************************************************/
int32_t getAngleEstimateFromAcc
(uint8_t axis
) {
return GYRO_ACC_FACTOR
* (int32_t)filteredAcc
[axis
];
}
void setStaticAttitudeAngles
(void) {
#ifdef ATTITUDE_USE_ACC_SENSORS
angle
[PITCH
] = getAngleEstimateFromAcc
(PITCH
);
angle
[ROLL
] = getAngleEstimateFromAcc
(ROLL
);
#else
angle
[PITCH
] = angle
[ROLL
] = 0;
#endif
}
/************************************************************************
* Neutral Readings
************************************************************************/
void attitude_setNeutral
(void) {
// Servo_Off(); // disable servo output. TODO: Why bother? The servos are going to make a jerk anyway.
dynamicParams.
AxisCoupling1 = dynamicParams.
AxisCoupling2 = 0;
dynamicOffset
[PITCH
] = dynamicOffset
[ROLL
] = 0;
correctionSum
[PITCH
] = correctionSum
[ROLL
] = 0;
// Calibrate hardware.
analog_calibrate
();
// reset gyro readings
rate
[PITCH
] = rate
[ROLL
] = yawRate
= 0;
// reset gyro integrals to acc guessing
setStaticAttitudeAngles
();
yawAngle
= 0;
// update compass course to current heading
compassCourse
= compassHeading
;
// Inititialize YawGyroIntegral value with current compass heading
yawGyroHeading
= (int32_t)compassHeading
* GYRO_DEG_FACTOR_YAW
;
// Servo_On(); //enable servo output
}
/************************************************************************
* Get sensor data from the analog module, and release the ADC
* TODO: Ultimately, the analog module could do this (instead of dumping
* the values into variables).
* The rate variable end up in a range of about [-1024, 1023].
* When scaled down by CONTROL_SCALING, the interval is about [-256, 256].
*************************************************************************/
void getAnalogData
(void) {
uint8_t axis
;
for (axis
=PITCH
; axis
<=ROLL
; axis
++) {
rate_PID
[axis
] = (gyro_PID
[axis
] + dynamicOffset
[axis
]) / HIRES_GYRO_INTEGRATION_FACTOR
;
rate
[axis
] = (gyro_ATT
[axis
] + dynamicOffset
[axis
]) / HIRES_GYRO_INTEGRATION_FACTOR
;
differential
[axis
] = gyroD
[axis
];
}
yawRate
= yawGyro
+ dynamicOffsetYaw
;
// We are done reading variables from the analog module.
// Interrupt-driven sensor reading may restart.
analogDataReady
= 0;
analog_start
();
}
/*
* This is the standard flight-style coordinate system transformation
* (from airframe-local axes to a ground-based system). For some reason
* the MK uses a left-hand coordinate system. The tranformation has been
* changed accordingly.
*/
void trigAxisCoupling
(void) {
int16_t cospitch
= int_cos
(angle
[PITCH
]);
int16_t cosroll
= int_cos
(angle
[ROLL
]);
int16_t sinroll
= int_sin
(angle
[ROLL
]);
int16_t tanpitch
= int_tan
(angle
[PITCH
]);
#define ANTIOVF 1024
ACRate
[PITCH
] = ((int32_t) rate
[PITCH
] * cosroll
- (int32_t)yawRate
* sinroll
) / (int32_t)MATH_UNIT_FACTOR
;
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
));
ACYawRate
= ((int32_t) rate
[PITCH
] * sinroll
) / cospitch
+ ((int32_t)yawRate
* cosroll
) / cospitch
;
}
void integrate
(void) {
// First, perform axis coupling. If disabled xxxRate is just copied to ACxxxRate.
uint8_t axis
;
if(!looping
&& (staticParams.
GlobalConfig & CFG_AXIS_COUPLING_ACTIVE
)) {
// The rotary rate limiter bit is abused for selecting axis coupling algorithm instead.
trigAxisCoupling
();
} else {
ACRate
[PITCH
] = rate
[PITCH
];
ACRate
[ROLL
] = rate
[ROLL
];
ACYawRate
= yawRate
;
}
/*
* Yaw
* Calculate yaw gyro integral (~ to rotation angle)
* Limit yawGyroHeading proportional to 0 deg to 360 deg
*/
yawGyroHeading
+= ACYawRate
;
// Why is yawAngle not wrapped 'round?
yawAngle
+= ACYawRate
;
if(yawGyroHeading
>= YAWOVER360
) {
yawGyroHeading
-= YAWOVER360
; // 360 deg. wrap
} else if(yawGyroHeading
< 0) {
yawGyroHeading
+= YAWOVER360
;
}
/*
* Pitch axis integration and range boundary wrap.
*/
for (axis
=PITCH
; axis
<=ROLL
; axis
++) {
angle
[axis
] += ACRate
[axis
];
if(angle
[axis
] > PITCHROLLOVER180
) {
angle
[axis
] -= PITCHROLLOVER360
;
} else if (angle
[axis
] <= -PITCHROLLOVER180
) {
angle
[axis
] += PITCHROLLOVER360
;
}
}
}
/************************************************************************
* A kind of 0'th order integral correction, that corrects the integrals
* directly. This is the "gyroAccFactor" stuff in the original code.
* There is (there) also a drift compensation
* - it corrects the differential of the integral = the gyro offsets.
* That should only be necessary with drifty gyros like ENC-03.
************************************************************************/
void correctIntegralsByAcc0thOrder
(void) {
// TODO: Consider changing this to: Only correct when integrals are less than ...., or only correct when angular velocities
// are less than ....., or reintroduce Kalman.
// Well actually the Z axis acc. check is not so silly.
uint8_t axis
;
int32_t correction
;
if(!looping
&& acc
[Z
] >= -dynamicParams.
UserParams[7] && acc
[Z
] <= dynamicParams.
UserParams[7]) {
DebugOut.
Digital[0] = 1;
uint8_t permilleAcc
= staticParams.
GyroAccFactor; // NOTE!!! The meaning of this value has changed!!
uint8_t debugFullWeight
= 1;
int32_t accDerived
;
if((maxControl
[PITCH
] > 64) || (maxControl
[ROLL
] > 64)) { // reduce effect during stick commands
permilleAcc
/= 2;
debugFullWeight
= 0;
}
if(abs(controlYaw
) > 25) { // reduce further if yaw stick is active
permilleAcc
/= 2;
debugFullWeight
= 0;
}
/*
* Add to each sum: The amount by which the angle is changed just below.
*/
for (axis
=PITCH
; axis
<=ROLL
; axis
++) {
accDerived
= getAngleEstimateFromAcc
(axis
);
DebugOut.
Analog[9 + axis
] = (10 * accDerived
) / GYRO_DEG_FACTOR_PITCHROLL
;
// 1000 * the correction amount that will be added to the gyro angle in next line.
correction
= angle
[axis
]; //(permilleAcc * (accDerived - angle[axis])) / 1000;
angle
[axis
] = ((int32_t)(1000 - permilleAcc
) * angle
[axis
] + (int32_t)permilleAcc
* accDerived
) / 1000L;
correctionSum
[axis
] += angle
[axis
] - correction
;
// There should not be a risk of overflow here, since the integrals do not exceed a few 100000.
// change = ((1000 - permilleAcc) * angle[axis] + permilleAcc * accDerived) / 1000 - angle[axis]
// = (1000 * angle[axis] - permilleAcc * angle[axis] + permilleAcc * accDerived) / 1000 - angle[axis]
// = (- permilleAcc * angle[axis] + permilleAcc * accDerived) / 1000
// = permilleAcc * (accDerived - angle[axis]) / 1000
// Experiment: Do not acutally apply the correction. See if drift compensation does that.
// angle[axis] += correction / 1000;
}
DebugOut.
Digital[1] = debugFullWeight
;
} else {
DebugOut.
Digital[0] = 0;
}
}
/************************************************************************
* This is an attempt to correct not the error in the angle integrals
* (that happens in correctIntegralsByAcc0thOrder above) but rather the
* cause of it: Gyro drift, vibration and rounding errors.
* All the corrections made in correctIntegralsByAcc0thOrder over
* DRIFTCORRECTION_TIME cycles are summed up. This number is
* then divided by DRIFTCORRECTION_TIME to get the approx.
* correction that should have been applied to each iteration to fix
* the error. This is then added to the dynamic offsets.
************************************************************************/
// 2 times / sec. = 488/2
#define DRIFTCORRECTION_TIME 256L
void driftCorrection
(void) {
static int16_t timer
= DRIFTCORRECTION_TIME
;
int16_t deltaCorrection
;
uint8_t axis
;
if (! --timer
) {
timer
= DRIFTCORRECTION_TIME
;
for (axis
=PITCH
; axis
<=ROLL
; axis
++) {
// Take the sum of corrections applied, add it to delta
deltaCorrection
= ((correctionSum
[axis
] + DRIFTCORRECTION_TIME
/ 2) * HIRES_GYRO_INTEGRATION_FACTOR
) / DRIFTCORRECTION_TIME
;
// Add the delta to the compensation. So positive delta means, gyro should have higher value.
dynamicOffset
[axis
] += deltaCorrection
/ staticParams.
GyroAccTrim;
CHECK_MIN_MAX
(dynamicOffset
[axis
], -staticParams.
DriftComp, staticParams.
DriftComp);
DebugOut.
Analog[11 + axis
] = correctionSum
[axis
];
DebugOut.
Analog[28 + axis
] = dynamicOffset
[axis
];
correctionSum
[axis
] = 0;
}
}
}
/************************************************************************
* Main procedure.
************************************************************************/
void calculateFlightAttitude
(void) {
getAnalogData
();
integrate
();
DebugOut.
Analog[6] = ACRate
[PITCH
];
DebugOut.
Analog[7] = ACRate
[ROLL
];
DebugOut.
Analog[8] = ACYawRate
;
DebugOut.
Analog[3] = rate_PID
[PITCH
];
DebugOut.
Analog[4] = rate_PID
[ROLL
];
DebugOut.
Analog[5] = yawRate
;
#ifdef ATTITUDE_USE_ACC_SENSORS
correctIntegralsByAcc0thOrder
();
driftCorrection
();
#endif
}
/*
void updateCompass(void) {
int16_t w, v, r,correction, error;
if(compassCalState && !(MKFlags & MKFLAG_MOTOR_RUN)) {
setCompassCalState();
} else {
// get maximum attitude angle
w = abs(pitchAngle / 512);
v = abs(rollAngle / 512);
if(v > w) w = v;
correction = w / 8 + 1;
// calculate the deviation of the yaw gyro heading and the compass heading
if (compassHeading < 0) error = 0; // disable yaw drift compensation if compass heading is undefined
else error = ((540 + compassHeading - (yawGyroHeading / GYRO_DEG_FACTOR_YAW)) % 360) - 180;
if(abs(yawRate) > 128) { // spinning fast
error = 0;
}
if(!badCompassHeading && w < 25) {
if(updateCompassCourse) {
beep(200);
yawGyroHeading = (int32_t)compassHeading * GYRO_DEG_FACTOR_YAW;
compassCourse = (int16_t)(yawGyroHeading / GYRO_DEG_FACTOR_YAW);
updateCompassCourse = 0;
}
}
yawGyroHeading += (error * 8) / correction;
w = (w * dynamicParams.CompassYawEffect) / 32;
w = dynamicParams.CompassYawEffect - w;
if(w >= 0) {
if(!badCompassHeading) {
v = 64 + (maxControlPitch + maxControlRoll) / 8;
// calc course deviation
r = ((540 + (yawGyroHeading / GYRO_DEG_FACTOR_YAW) - compassCourse) % 360) - 180;
v = (r * w) / v; // align to compass course
// limit yaw rate
w = 3 * dynamicParams.CompassYawEffect;
if (v > w) v = w;
else if (v < -w) v = -w;
yawAngle += v;
}
else
{ // wait a while
badCompassHeading--;
}
}
else { // ignore compass at extreme attitudes for a while
badCompassHeading = 500;
}
}
}
*/
/*
* This is part of an experiment to measure average sensor offsets caused by motor vibration,
* and to compensate them away. It brings about some improvement, but no miracles.
* As long as the left stick is kept in the start-motors position, the dynamic compensation
* will measure the effect of vibration, to use for later compensation. So, one should keep
* the stick in the start-motors position for a few seconds, till all motors run (at the wrong
* speed unfortunately... must find a better way)
*/
/*
void attitude_startDynamicCalibration(void) {
dynamicCalPitch = dynamicCalRoll = dynamicCalYaw = dynamicCalCount = 0;
savedDynamicOffsetPitch = savedDynamicOffsetRoll = 1000;
}
void attitude_continueDynamicCalibration(void) {
// measure dynamic offset now...
dynamicCalPitch += hiResPitchGyro;
dynamicCalRoll += hiResRollGyro;
dynamicCalYaw += rawYawGyroSum;
dynamicCalCount++;
// Param6: Manual mode. The offsets are taken from Param7 and Param8.
if (dynamicParams.UserParam6 || 1) { // currently always enabled.
// manual mode
dynamicOffsetPitch = dynamicParams.UserParam7 - 128;
dynamicOffsetRoll = dynamicParams.UserParam8 - 128;
} else {
// use the sampled value (does not seem to work so well....)
dynamicOffsetPitch = savedDynamicOffsetPitch = -dynamicCalPitch / dynamicCalCount;
dynamicOffsetRoll = savedDynamicOffsetRoll = -dynamicCalRoll / dynamicCalCount;
dynamicOffsetYaw = -dynamicCalYaw / dynamicCalCount;
}
// keep resetting these meanwhile, to avoid accumulating errors.
setStaticAttitudeIntegrals();
yawAngle = 0;
}
*/