// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + 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 pitchRate
, rollRate
, yawRate
;
// With different (less) filtering
int16_t pitchRate_PID
, rollRate_PID
;
int16_t pitchDifferential
, rollDifferential
;
/*
* 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 ACPitchRate
, ACRollRate
, ACYawRate
;
/*
* Gyro integrals. These are the rotation angles of the airframe compared to the
* horizontal plane, yaw relative to yaw at start.
*/
int32_t pitchAngle
, rollAngle
, 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
int32_t turnOver180
= GYRO_DEG_FACTOR_PITCHROLL
* 180L;
int32_t turnOver360
= GYRO_DEG_FACTOR_PITCHROLL
* 360L;
int32_t pitchCorrectionSum
= 0, rollCorrectionSum
= 0;
/*
* Experiment: Compensating for dynamic-induced gyro biasing.
*/
int16_t dynamicOffsetPitch
= 0, dynamicOffsetRoll
= 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 sinc: 1) the angles are rather 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 getPitchAngleEstimateFromAcc
(void) {
return GYRO_ACC_FACTOR
* (int32_t)filteredPitchAxisAcc
;
}
int32_t getRollAngleEstimateFromAcc
(void) {
return GYRO_ACC_FACTOR
* (int32_t)filteredRollAxisAcc
;
}
void setStaticAttitudeAngles
(void) {
#ifdef ATTITUDE_USE_ACC_SENSORS
pitchAngle
= getPitchAngleEstimateFromAcc
();
rollAngle
= getRollAngleEstimateFromAcc
();
#else
pitchAngle
= 0;
rollAngle
= 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;
dynamicOffsetPitch
= dynamicOffsetRoll
= 0;
// Calibrate hardware.
analog_calibrate
();
// reset gyro readings
pitchRate
= rollRate
= 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).
*************************************************************************/
void getAnalogData
(void) {
// For the differential calculation. Diff. is not supported right now.
// int16_t d2Pitch, d2Roll;
pitchRate_PID
= (hiResPitchGyro
+ dynamicOffsetPitch
) / HIRES_GYRO_INTEGRATION_FACTOR
;
pitchRate
= (filteredHiResPitchGyro
+ dynamicOffsetPitch
) / HIRES_GYRO_INTEGRATION_FACTOR
;
pitchDifferential
= pitchGyroD
;
rollRate_PID
= (hiResRollGyro
+ dynamicOffsetRoll
) / HIRES_GYRO_INTEGRATION_FACTOR
;
rollRate
= (filteredHiResRollGyro
+ dynamicOffsetRoll
) / HIRES_GYRO_INTEGRATION_FACTOR
;
rollDifferential
= rollGyroD
;
yawRate
= yawGyro
+ dynamicOffsetYaw
;
// We are done reading variables from the analog module. Interrupt-driven sensor reading may restart.
// TODO: Is that not a little early to measure for next control invocation?
analogDataReady
= 0;
analog_start
();
}
/************************************************************************
* Axis coupling, H&I Style
* Currently not working (and there is a bug in it,
* which causes unstable flight in heading-hold mode).
************************************************************************/
void H_and_I_axisCoupling
(void) {
int32_t tmpl
= 0, tmpl2
= 0, tmp13
= 0, tmp14
= 0;
int16_t CouplingNickRoll
= 0, CouplingRollNick
= 0;
tmp13
= (rollRate
* pitchAngle
) / 2048L;
tmp13
*= dynamicParams.
AxisCoupling2; // 65
tmp13
/= 4096L;
CouplingNickRoll
= tmp13
;
tmp14
= (pitchRate
* rollAngle
) / 2048L;
tmp14
*= dynamicParams.
AxisCoupling2; // 65
tmp14
/= 4096L;
CouplingRollNick
= tmp14
;
tmp14
-= tmp13
;
ACYawRate
= yawRate
+ tmp14
;
/*
if(!dynamicParams.AxisCouplingYawCorrection) ACYawRate = yawRate - tmp14 / 2; // force yaw
else ACYawRate
*/
tmpl
= ((yawRate
+ tmp14
) * pitchAngle
) / 2048L;
tmpl
*= dynamicParams.
AxisCoupling1;
tmpl
/= 4096L;
tmpl2
= ((yawRate
+ tmp14
) * rollAngle
) / 2048L;
tmpl2
*= dynamicParams.
AxisCoupling1;
tmpl2
/= 4096L;
// if(abs(yawRate > 64)) {
// if(labs(tmpl) > 128 || labs(tmpl2) > 128) FunnelCourse = 1;
// }
ACPitchRate
= pitchRate
- tmpl2
+ tmpl
/ 100L;
ACRollRate
= rollRate
+ tmpl
- tmpl2
/ 100L;
}
/*
* 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
(pitchAngle
);
int16_t cosroll
= int_cos
(rollAngle
);
int16_t sinroll
= int_sin
(rollAngle
);
int16_t tanpitch
= int_tan
(pitchAngle
);
#define ANTIOVF 1024
ACPitchRate
= ((int32_t)pitchRate
* cosroll
+ (int32_t)yawRate
* sinroll
) / (int32_t)MATH_UNIT_FACTOR
;
ACRollRate
= rollRate
+ (((int32_t)pitchRate
* sinroll
/ ANTIOVF
* tanpitch
- (int32_t)yawRate
* int_cos
(rollAngle
) / ANTIOVF
* tanpitch
) / ((int32_t)MATH_UNIT_FACTOR
/ ANTIOVF
* MATH_UNIT_FACTOR
));
ACYawRate
= (-(int32_t)pitchRate
* sinroll
) / cospitch
+ ((int32_t)yawRate
* cosroll
) / cospitch
;
}
void integrate
(void) {
// First, perform axis coupling. If disabled xxxRate is just copied to ACxxxRate.
if(!looping
&& (staticParams.
GlobalConfig & CFG_AXIS_COUPLING_ACTIVE
)) {
// The rotary rate limiter bit is abused for selecting axis coupling algorithm instead.
if (staticParams.
GlobalConfig & CFG_ROTARY_RATE_LIMITER
)
trigAxisCoupling
();
else
H_and_I_axisCoupling
();
} else {
ACPitchRate
= pitchRate
;
ACRollRate
= rollRate
;
ACYawRate
= yawRate
;
}
DebugOut.
Analog[3] = pitchRate
;
DebugOut.
Analog[3 + 3] = ACPitchRate
;
DebugOut.
Analog[4] = rollRate
;
DebugOut.
Analog[4 + 3] = ACRollRate
;
DebugOut.
Analog[5] = yawRate
;
DebugOut.
Analog[5 + 3] = ACYawRate
;
/*
DebugOut.Analog[9] = int_cos(pitchAngle);
DebugOut.Analog[10] = int_sin(pitchAngle);
DebugOut.Analog[11] = int_tan(pitchAngle);
*/
/*
* Yaw
* Calculate yaw gyro integral (~ to rotation angle)
* Limit yawGyroHeading proportional to 0 deg to 360 deg
*/
yawGyroHeading
+= ACYawRate
;
yawAngle
+= ACYawRate
;
if(yawGyroHeading
>= (360L * GYRO_DEG_FACTOR_YAW
)) yawGyroHeading
-= 360L * GYRO_DEG_FACTOR_YAW
; // 360 deg. wrap
if(yawGyroHeading
< 0) yawGyroHeading
+= 360L * GYRO_DEG_FACTOR_YAW
;
/*
* Pitch axis integration and range boundary wrap.
*/
pitchAngle
+= ACPitchRate
;
if(pitchAngle
> turnOver180
) {
pitchAngle
-= turnOver360
;
} else if (pitchAngle
<= -turnOver180
) {
pitchAngle
+= turnOver360
;
}
/*
* Pitch axis integration and range boundary wrap.
*/
rollAngle
+= ACRollRate
;
if(rollAngle
> turnOver180
) {
rollAngle
-= turnOver360
;
} else if (rollAngle
<= -turnOver180
) {
rollAngle
+= turnOver360
;
}
}
/************************************************************************
* 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 what I would call a "minus 1st order correction"
* - 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.
if(!looping
&& //((ZAxisAcc >= -4) || (MKFlags & MKFLAG_MOTOR_RUN))) { // if not looping in any direction
ZAxisAcc
>= -dynamicParams.
UserParams[7] && ZAxisAcc
<= 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 accDerivedPitch
= getPitchAngleEstimateFromAcc
();
int32_t accDerivedRoll
= getRollAngleEstimateFromAcc
();
if((maxControlPitch
> 64) || (maxControlRoll
> 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.
*/
pitchCorrectionSum
+= permilleAcc
* (accDerivedPitch
- pitchAngle
);
rollCorrectionSum
+= permilleAcc
* (accDerivedRoll
- rollAngle
);
// There should not be a risk of overflow here, since the integrals do not exceed a few 100000.
pitchAngle
= ((int32_t)(1000 - permilleAcc
) * pitchAngle
+ (int32_t)permilleAcc
* accDerivedPitch
) / 1000L;
rollAngle
= ((int32_t)(1000 - permilleAcc
) * rollAngle
+ (int32_t)permilleAcc
* accDerivedRoll
) / 1000L;
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
* MINUSFIRSTORDERCORRECTION_TIME cycles are summed up. This number is
* then divided by MINUSFIRSTORDERCORRECTION_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.
#define DRIFTCORRECTION_TIME 488/2
void driftCompensation
(void) {
static int16_t timer
= DRIFTCORRECTION_TIME
;
int16_t deltaCompensation
;
if (! --timer
) {
timer
= DRIFTCORRECTION_TIME
;
deltaCompensation
= ((pitchCorrectionSum
+ 1000L * DRIFTCORRECTION_TIME
/ 2) / 1000 / DRIFTCORRECTION_TIME
);
CHECK_MIN_MAX
(deltaCompensation
, -staticParams.
DriftComp, staticParams.
DriftComp);
dynamicOffsetPitch
+= deltaCompensation
/ staticParams.
GyroAccTrim;
deltaCompensation
= ((rollCorrectionSum
+ 1000L * DRIFTCORRECTION_TIME
/ 2) / 1000 / DRIFTCORRECTION_TIME
);
CHECK_MIN_MAX
(deltaCompensation
, -staticParams.
DriftComp, staticParams.
DriftComp);
dynamicOffsetRoll
+= deltaCompensation
/ staticParams.
GyroAccTrim;
pitchCorrectionSum
= rollCorrectionSum
= 0;
DebugOut.
Analog[28] = dynamicOffsetPitch
;
DebugOut.
Analog[29] = dynamicOffsetRoll
;
}
}
/************************************************************************
* Main procedure.
************************************************************************/
void calculateFlightAttitude
(void) {
getAnalogData
();
integrate
();
#ifdef ATTITUDE_USE_ACC_SENSORS
correctIntegralsByAcc0thOrder
();
driftCompensation
();
#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;
}
*/