Rev 1872 |
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 example: 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"
// For scope debugging only!
#include "rc.h"
// where our main data flow comes from.
#include "analog.h"
#include "configuration.h"
#include "output.h"
// Some calculations are performed depending on some stick related things.
#include "controlMixer.h"
// For Servo_On / Off
// #include "timer2.h"
#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_ATT
[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], yawAngleDiff
;
int readingHeight
= 0;
// Yaw angle and compass stuff.
// This is updated/written from MM3. Negative angle indicates invalid data.
int16_t compassHeading
= -1;
// This is NOT updated from MM3. Negative angle indicates invalid data.
int16_t compassCourse
= -1;
// The difference between the above 2 (heading - course) on a -180..179 degree interval.
// Not necessary. Never read anywhere.
// int16_t compassOffCourse = 0;
uint8_t updateCompassCourse
= 0;
uint8_t compassCalState
= 0;
uint16_t ignoreCompassTimer
= 500;
int32_t yawGyroHeading
; // Yaw Gyro Integral supported by compass
int16_t yawGyroDrift
;
#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 };
// For NaviCTRL use.
int16_t averageAcc
[2] = { 0, 0 }, averageAccCount
= 0;
/*
* Experiment: Compensating for dynamic-induced gyro biasing.
*/
int16_t driftComp
[2] = { 0, 0 }, driftCompYaw
= 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;
driftComp
[PITCH
] = driftComp
[ROLL
] = yawGyroDrift
= driftCompYaw
= 0;
correctionSum
[PITCH
] = correctionSum
[ROLL
] = 0;
// Calibrate hardware.
analog_calibrate
();
// reset gyro integrals to acc guessing
setStaticAttitudeAngles
();
yawAngleDiff
= 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].
*************************************************************************/
void getAnalogData
(void) {
uint8_t axis
;
for (axis
= PITCH
; axis
<= ROLL
; axis
++) {
rate_PID
[axis
] = gyro_PID
[axis
] /* / HIRES_GYRO_INTEGRATION_FACTOR */ + driftComp
[axis
];
rate_ATT
[axis
] = gyro_ATT
[axis
] /* / HIRES_GYRO_INTEGRATION_FACTOR */ + driftComp
[axis
];
differential
[axis
] = gyroD
[axis
];
averageAcc
[axis
] += acc
[axis
];
}
averageAccCount
++;
yawRate
= yawGyro
+ driftCompYaw
;
// 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
]);
ACRate
[PITCH
] = (((int32_t)rate_ATT
[PITCH
] * cosroll
- (int32_t)yawRate
* sinroll
) >> MATH_UNIT_FACTOR_LOG
);
ACRate
[ROLL
] = rate_ATT
[ROLL
] + (((((int32_t)rate_ATT
[PITCH
] * sinroll
+ (int32_t)yawRate
* cosroll
) >> MATH_UNIT_FACTOR_LOG
) * int_tan
(
angle
[PITCH
])) >> MATH_UNIT_FACTOR_LOG
);
ACYawRate
= ((int32_t)rate_ATT
[PITCH
] * sinroll
+ (int32_t)yawRate
* cosroll
) / cospitch
;
ACYawRate
= ((int32_t)rate_ATT
[PITCH
] * sinroll
+ (int32_t)yawRate
* cosroll
) / cospitch
;
}
// 480 usec with axis coupling - almost no time without.
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
)) {
trigAxisCoupling
();
} else {
ACRate
[PITCH
] = rate_ATT
[PITCH
];
ACRate
[ROLL
] = rate_ATT
[ROLL
];
ACYawRate
= yawRate
;
}
/*
* Yaw
* Calculate yaw gyro integral (~ to rotation angle)
* Limit yawGyroHeading proportional to 0 deg to 360 deg
*/
yawGyroHeading
+= ACYawRate
;
yawAngleDiff
+= yawRate
;
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 temp
;
if (!looping
&& acc
[Z
] >= -dynamicParams.
UserParams[7] && acc
[Z
]
<= dynamicParams.
UserParams[7]) {
DebugOut.
Digital[0] |= DEBUG_ACC0THORDER
;
uint8_t permilleAcc
= staticParams.
GyroAccFactor; // NOTE!!! The meaning of this value has changed!!
uint8_t debugFullWeight
= 1;
int32_t accDerived
;
if ((controlYaw
< -64) || (controlYaw
> 64)) { // reduce further if yaw stick is active
permilleAcc
/= 2;
debugFullWeight
= 0;
}
if ((maxControl
[PITCH
] > 64) || (maxControl
[ROLL
] > 64)) { // reduce effect during stick commands
permilleAcc
/= 2;
debugFullWeight
= 0;
}
if (debugFullWeight
)
DebugOut.
Digital[1] |= DEBUG_ACC0THORDER
;
else
DebugOut.
Digital[1] &= ~DEBUG_ACC0THORDER
;
/*
* 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.
temp
= angle
[axis
]; //(permilleAcc * (accDerived - angle[axis])) / 1000;
angle
[axis
] = ((int32_t) (1000L - permilleAcc
) * temp
+ (int32_t) permilleAcc
* accDerived
) / 1000L;
correctionSum
[axis
] += angle
[axis
] - temp
;
}
} else {
DebugOut.
Digital[0] &= ~DEBUG_ACC0THORDER
;
DebugOut.
Digital[1] &= ~DEBUG_ACC0THORDER
;
DebugOut.
Analog[9] = 0;
DebugOut.
Analog[10] = 0;
DebugOut.
Analog[16] = 0;
DebugOut.
Analog[17] = 0;
// experiment: Kill drift compensation updates when not flying smooth.
correctionSum
[PITCH
] = correctionSum
[ROLL
] = 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
;
int16_t round
;
uint8_t axis
;
if (!--timer
) {
timer
= DRIFTCORRECTION_TIME
;
for (axis
= PITCH
; axis
<= ROLL
; axis
++) {
// Take the sum of corrections applied, add it to delta
if (correctionSum
[axis
] >=0)
round
= DRIFTCORRECTION_TIME
/ 2;
else
round
= -DRIFTCORRECTION_TIME
/ 2;
deltaCorrection
= (correctionSum
[axis
] + round
) / DRIFTCORRECTION_TIME
;
// Add the delta to the compensation. So positive delta means, gyro should have higher value.
driftComp
[axis
] += deltaCorrection
/ staticParams.
GyroAccTrim;
CHECK_MIN_MAX
(driftComp
[axis
], -staticParams.
DriftComp, staticParams.
DriftComp);
// DebugOut.Analog[11 + axis] = correctionSum[axis];
DebugOut.
Analog[16 + axis
] = correctionSum
[axis
];
DebugOut.
Analog[28 + axis
] = driftComp
[axis
];
correctionSum
[axis
] = 0;
}
}
}
/************************************************************************
* Main procedure.
************************************************************************/
void calculateFlightAttitude
(void) {
getAnalogData
();
integrate
();
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
)) {
if (controlMixer_testCompassCalState
()) {
compassCalState
++;
if (compassCalState
< 5)
beepNumber
(compassCalState
);
else
beep
(1000);
}
} else {
// get maximum attitude angle
w
= abs(angle
[PITCH
] / 512);
v
= abs(angle
[ROLL
] / 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 if (abs(yawRate
) > 128) { // spinning fast
error
= 0;
} else {
// compassHeading - yawGyroHeading, on a -180..179 deg interval.
error
= ((540 + compassHeading
- (yawGyroHeading
/ GYRO_DEG_FACTOR_YAW
))
% 360) - 180;
}
if (!ignoreCompassTimer
&& w
< 25) {
yawGyroDrift
+= error
;
// Basically this gets set if we are in "fix" mode, and when starting.
if (updateCompassCourse
) {
beep
(200);
yawGyroHeading
= (int32_t) compassHeading
* GYRO_DEG_FACTOR_YAW
;
compassCourse
= compassHeading
; //(int16_t)(yawGyroHeading / GYRO_DEG_FACTOR_YAW);
updateCompassCourse
= 0;
}
}
yawGyroHeading
+= (error
* 8) / correction
;
/*
w = (w * dynamicParams.CompassYawEffect) / 32;
w = dynamicParams.CompassYawEffect - w;
*/
w
= dynamicParams.
CompassYawEffect - (w
* dynamicParams.
CompassYawEffect)
/ 32;
// As readable formula:
// w = dynamicParams.CompassYawEffect * (1-w/32);
if (w
>= 0) { // maxAttitudeAngle < 32
if (!ignoreCompassTimer
) {
v
= 64 + (maxControl
[PITCH
] + maxControl
[ROLL
]) / 8;
// yawGyroHeading - compassCourse on a -180..179 degree interval.
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
;
yawAngleDiff
+= v
;
} else { // wait a while
ignoreCompassTimer
--;
}
} else { // ignore compass at extreme attitudes for a while
ignoreCompassTimer
= 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
driftCompPitch = dynamicParams.UserParam7 - 128;
driftCompRoll = dynamicParams.UserParam8 - 128;
} else {
// use the sampled value (does not seem to work so well....)
driftCompPitch = savedDynamicOffsetPitch = -dynamicCalPitch / dynamicCalCount;
driftCompRoll = savedDynamicOffsetRoll = -dynamicCalRoll / dynamicCalCount;
driftCompYaw = -dynamicCalYaw / dynamicCalCount;
}
// keep resetting these meanwhile, to avoid accumulating errors.
setStaticAttitudeIntegrals();
yawAngle = 0;
}
*/