Subversion Repositories FlightCtrl

Compare Revisions

Ignore whitespace Rev 2168 → Rev 2169

/branches/V0.88n S.BUS ATmega644 tempolo/Liesmich.txt
0,0 → 1,3
Siehe: http://www.mikrokopter.de/ucwiki/Futaba%20S.BUS
 
Hier sind nur die Files enthalten, die sich von der V0.88n unterscheiden.
/branches/V0.88n S.BUS ATmega644 tempolo/eeprom.c
0,0 → 1,632
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + www.MikroKopter.com
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Software Nutzungsbedingungen (english version: see below)
// + der Fa. HiSystems GmbH, Flachsmeerstrasse 2, 26802 Moormerland - nachfolgend Lizenzgeber genannt -
// + Der Lizenzgeber räumt dem Kunden ein nicht-ausschließliches, zeitlich und räumlich* unbeschränktes Recht ein, die im den
// + Mikrocontroller verwendete Firmware für die Hardware Flight-Ctrl, Navi-Ctrl, BL-Ctrl, MK3Mag & PC-Programm MikroKopter-Tool
// + - nachfolgend Software genannt - nur für private Zwecke zu nutzen.
// + Der Einsatz dieser Software ist nur auf oder mit Produkten des Lizenzgebers zulässig.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Die vom Lizenzgeber gelieferte Software ist urheberrechtlich geschützt. Alle Rechte an der Software sowie an sonstigen im
// + Rahmen der Vertragsanbahnung und Vertragsdurchführung überlassenen Unterlagen stehen im Verhältnis der Vertragspartner ausschließlich dem Lizenzgeber zu.
// + Die in der Software enthaltenen Copyright-Vermerke, Markenzeichen, andere Rechtsvorbehalte, Seriennummern sowie
// + sonstige der Programmidentifikation dienenden Merkmale dürfen vom Kunden nicht verändert oder unkenntlich gemacht werden.
// + Der Kunde trifft angemessene Vorkehrungen für den sicheren Einsatz der Software. Er wird die Software gründlich auf deren
// + Verwendbarkeit zu dem von ihm beabsichtigten Zweck testen, bevor er diese operativ einsetzt.
// + Die Haftung des Lizenzgebers wird - soweit gesetzlich zulässig - begrenzt in Höhe des typischen und vorhersehbaren
// + Schadens. Die gesetzliche Haftung bei Personenschäden und nach dem Produkthaftungsgesetz bleibt unberührt. Dem Lizenzgeber steht jedoch der Einwand
// + des Mitverschuldens offen.
// + Der Kunde trifft angemessene Vorkehrungen für den Fall, dass die Software ganz oder teilweise nicht ordnungsgemäß arbeitet.
// + Er wird die Software gründlich auf deren Verwendbarkeit zu dem von ihm beabsichtigten Zweck testen, bevor er diese operativ einsetzt.
// + Der Kunde wird er seine Daten vor Einsatz der Software nach dem Stand der Technik sichern.
// + Der Kunde ist darüber unterrichtet, dass der Lizenzgeber seine Daten im zur Vertragsdurchführung erforderlichen Umfang
// + und auf Grundlage der Datenschutzvorschriften erhebt, speichert, verarbeitet und, sofern notwendig, an Dritte übermittelt.
// + *) Die räumliche Nutzung bezieht sich nur auf den Einsatzort, nicht auf die Reichweite der programmierten Software.
// + #### ENDE DER NUTZUNGSBEDINGUNGEN ####'
// + Hinweis: Informationen über erweiterte Nutzungsrechte (wie z.B. Nutzung für nicht-private Zwecke) sind auf Anfrage per Email an info(@)hisystems.de verfügbar.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Software LICENSING TERMS
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + of HiSystems GmbH, Flachsmeerstrasse 2, 26802 Moormerland, Germany - the Licensor -
// + The Licensor grants the customer a non-exclusive license to use the microcontroller firmware of the Flight-Ctrl, Navi-Ctrl, BL-Ctrl, and MK3Mag hardware
// + (the Software) exclusively for private purposes. The License is unrestricted with respect to time and territory*.
// + The Software may only be used with the Licensor's products.
// + The Software provided by the Licensor is protected by copyright. With respect to the relationship between the parties to this
// + agreement, all rights pertaining to the Software and other documents provided during the preparation and execution of this
// + agreement shall be the property of the Licensor.
// + The information contained in the Software copyright notices, trademarks, other legal reservations, serial numbers and other
// + features that can be used to identify the program may not be altered or defaced by the customer.
// + The customer shall be responsible for taking reasonable precautions
// + for the safe use of the Software. The customer shall test the Software thoroughly regarding its suitability for the
// + intended purpose before implementing it for actual operation. The Licensor's liability shall be limited to the extent of typical and
// + foreseeable damage to the extent permitted by law, notwithstanding statutory liability for bodily injury and product
// + liability. However, the Licensor shall be entitled to the defense of contributory negligence.
// + The customer will take adequate precautions in the case, that the software is not working properly. The customer will test
// + the software for his purpose before any operational usage. The customer will backup his data before using the software.
// + The customer understands that the Licensor collects, stores and processes, and, where required, forwards, customer data
// + to third parties to the extent necessary for executing the agreement, subject to applicable data protection and privacy regulations.
// + *) The territory aspect only refers to the place where the Software is used, not its programmed range.
// + #### END OF LICENSING TERMS ####
// + Note: For information on license extensions (e.g. commercial use), please contact us at info(@)hisystems.de.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 
 
#ifndef EEMEM
#define EEMEM __attribute__ ((section (".eeprom")))
#endif
 
 
#include <avr/eeprom.h>
#include <string.h>
#include "eeprom.h"
#include "uart.h"
#include "led.h"
#include "main.h"
#include "fc.h"
#include "twimaster.h"
 
paramset_t EE_Parameter;
MixerTable_t Mixer;
uint8_t RequiredMotors;
 
 
uint8_t RAM_Checksum(uint8_t* pBuffer, uint16_t len)
{
uint8_t crc = 0xAA;
uint16_t i;
 
for(i=0; i<len; i++)
{
crc += pBuffer[i];
}
return crc;
}
 
uint8_t EEProm_Checksum(uint16_t EEAddr, uint16_t len)
{
uint8_t crc = 0xAA;
uint16_t off;
 
for(off=0; off<len; off++)
{
crc += eeprom_read_byte((uint8_t*)(EEAddr + off));;
}
return crc;
}
 
void ParamSet_DefaultStickMapping(void)
{
EE_Parameter.Kanalbelegung[K_GAS] = 1;
EE_Parameter.Kanalbelegung[K_ROLL] = 2;
EE_Parameter.Kanalbelegung[K_NICK] = 3;
EE_Parameter.Kanalbelegung[K_GIER] = 4;
EE_Parameter.Kanalbelegung[K_POTI1] = 5;
EE_Parameter.Kanalbelegung[K_POTI2] = 6;
EE_Parameter.Kanalbelegung[K_POTI3] = 7;
EE_Parameter.Kanalbelegung[K_POTI4] = 8;
EE_Parameter.Kanalbelegung[K_POTI5] = 9;
EE_Parameter.Kanalbelegung[K_POTI6] = 10;
EE_Parameter.Kanalbelegung[K_POTI7] = 11;
EE_Parameter.Kanalbelegung[K_POTI8] = 12;
}
 
 
/***************************************************/
/* Default Values for parameter set 1 */
/***************************************************/
void CommonDefaults(void)
{
EE_Parameter.Revision = EEPARAM_REVISION;
 
if(PlatinenVersion >= 20)
{
EE_Parameter.Gyro_D = 10;
EE_Parameter.Driftkomp = 0;
EE_Parameter.GyroAccFaktor = 27;
EE_Parameter.WinkelUmschlagNick = 78;
EE_Parameter.WinkelUmschlagRoll = 78;
}
else
{
EE_Parameter.Gyro_D = 3;
EE_Parameter.Driftkomp = 32;
EE_Parameter.GyroAccFaktor = 30;
EE_Parameter.WinkelUmschlagNick = 85;
EE_Parameter.WinkelUmschlagRoll = 85;
}
EE_Parameter.GyroAccAbgleich = 32; // 1/k
EE_Parameter.BitConfig = 0; // Looping usw.
EE_Parameter.GlobalConfig = CFG_ACHSENKOPPLUNG_AKTIV | CFG_KOMPASS_AKTIV | CFG_GPS_AKTIV | CFG_HOEHEN_SCHALTER;
EE_Parameter.ExtraConfig = CFG_GPS_AID | CFG2_VARIO_BEEP;
EE_Parameter.GlobalConfig3 = 0;//CFG3_VARIO_FAILSAFE;
EE_Parameter.Receiver = RECEIVER_JETI;
EE_Parameter.MotorSafetySwitch = 0;
EE_Parameter.ExternalControl = 0;
 
EE_Parameter.Gas_Min = 8; // Wert : 0-32
EE_Parameter.Gas_Max = 230; // Wert : 33-247
EE_Parameter.KompassWirkung = 64; // Wert : 0-247
 
EE_Parameter.Hoehe_MinGas = 30;
EE_Parameter.MaxHoehe = 255; // Wert : 0-247 255 -> Poti1
EE_Parameter.Hoehe_P = 15; // Wert : 0-32
EE_Parameter.Luftdruck_D = 30; // Wert : 0-247
EE_Parameter.Hoehe_ACC_Wirkung = 0; // Wert : 0-247
EE_Parameter.Hoehe_HoverBand = 8; // Wert : 0-247
EE_Parameter.Hoehe_GPS_Z = 20; // Wert : 0-247
EE_Parameter.Hoehe_StickNeutralPoint = 0;// Wert : 0-247 (0 = Hover-Estimation)
EE_Parameter.Hoehe_Verstaerkung = 15; // Wert : 0-50 (15 -> ca. +/- 5m/sek bei Stick-Voll-Ausschlag)
 
EE_Parameter.UserParam1 = 0; // zur freien Verwendung
EE_Parameter.UserParam2 = 0; // zur freien Verwendung
EE_Parameter.UserParam3 = 0; // zur freien Verwendung
EE_Parameter.UserParam4 = 0; // zur freien Verwendung
EE_Parameter.UserParam5 = 0; // zur freien Verwendung
EE_Parameter.UserParam6 = 0; // zur freien Verwendung
EE_Parameter.UserParam7 = 0; // zur freien Verwendung
EE_Parameter.UserParam8 = 0; // zur freien Verwendung
 
EE_Parameter.ServoNickControl = 128; // Wert : 0-247 // Stellung des Servos
EE_Parameter.ServoNickComp = 50; // Wert : 0-247 // Einfluss Gyro/Servo
EE_Parameter.ServoCompInvert = 2; // Wert : 0-247 // Richtung Einfluss Gyro/Servo
EE_Parameter.ServoNickMin = 15; // Wert : 0-247 // Anschlag
EE_Parameter.ServoNickMax = 230; // Wert : 0-247 // Anschlag
EE_Parameter.ServoNickRefresh = 4;
EE_Parameter.Servo3 = 125;
EE_Parameter.Servo4 = 125;
EE_Parameter.Servo5 = 125;
EE_Parameter.ServoRollControl = 128; // Wert : 0-247 // Stellung des Servos
EE_Parameter.ServoRollComp = 85; // Wert : 0-247 // Einfluss Gyro/Servo
EE_Parameter.ServoRollMin = 70; // Wert : 0-247 // Anschlag
EE_Parameter.ServoRollMax = 220; // Wert : 0-247 // Anschlag
EE_Parameter.ServoManualControlSpeed = 60;
EE_Parameter.CamOrientation = 0; // Wert : 0-24 -> 0-360 -> 15° steps
 
EE_Parameter.J16Bitmask = 95;
EE_Parameter.J17Bitmask = 243;
EE_Parameter.WARN_J16_Bitmask = 0xAA;
EE_Parameter.WARN_J17_Bitmask = 0xAA;
EE_Parameter.J16Timing = 40;
EE_Parameter.J17Timing = 40;
 
EE_Parameter.LoopGasLimit = 50;
EE_Parameter.LoopThreshold = 90; // Wert: 0-247 Schwelle für Stickausschlag
EE_Parameter.LoopHysterese = 50;
 
EE_Parameter.NaviGpsModeControl = 254; // 254 -> Poti 2
EE_Parameter.NaviGpsGain = 100;
EE_Parameter.NaviGpsP = 90;
EE_Parameter.NaviGpsI = 90;
EE_Parameter.NaviGpsD = 90;
EE_Parameter.NaviGpsPLimit = 75;
EE_Parameter.NaviGpsILimit = 85;
EE_Parameter.NaviGpsDLimit = 75;
EE_Parameter.NaviGpsACC = 0;
EE_Parameter.NaviGpsMinSat = 6;
EE_Parameter.NaviStickThreshold = 8;
EE_Parameter.NaviWindCorrection = 90;
EE_Parameter.NaviAccCompensation = 42;
EE_Parameter.NaviOperatingRadius = 245;
EE_Parameter.NaviAngleLimitation = 140;
EE_Parameter.NaviPH_LoginTime = 5;
EE_Parameter.OrientationAngle = 0;
EE_Parameter.CareFreeModeControl = 0;
EE_Parameter.UnterspannungsWarnung = 33; // Wert : 0-247 ( Automatische Zellenerkennung bei < 50)
EE_Parameter.NotGas = 65; // Wert : 0-247 // Gaswert bei Empangsverlust (ggf. in Prozent)
EE_Parameter.NotGasZeit = 90; // Wert : 0-247 // Zeit bis auf NotGas geschaltet wird, wg. Rx-Problemen
EE_Parameter.MotorSmooth = 0;
EE_Parameter.ComingHomeAltitude = 0; // 0 = don't change
EE_Parameter.FailSafeTime = 0; // 0 = off
EE_Parameter.MaxAltitude = 150; // 0 = off
EE_Parameter.AchsKopplung1 = 90;
EE_Parameter.AchsKopplung2 = 55;
EE_Parameter.FailsafeChannel = 0;
EE_Parameter.ServoFilterNick = 0;
EE_Parameter.ServoFilterRoll = 0;
}
/*
void ParamSet_DefaultSet1(void) // sport
{
CommonDefaults();
EE_Parameter.Stick_P = 14; // Wert : 1-20
EE_Parameter.Stick_D = 16; // Wert : 0-20
EE_Parameter.StickGier_P = 12; // Wert : 1-20
EE_Parameter.Gyro_P = 80; // Wert : 0-247
EE_Parameter.Gyro_I = 150; // Wert : 0-247
EE_Parameter.Gyro_Gier_P = 80; // Wert : 0-247
EE_Parameter.Gyro_Gier_I = 150; // Wert : 0-247
EE_Parameter.Gyro_Stability = 6; // Wert : 1-8
EE_Parameter.I_Faktor = 32;
EE_Parameter.CouplingYawCorrection = 1;
EE_Parameter.GyroAccAbgleich = 16; // 1/k;
EE_Parameter.DynamicStability = 100;
memcpy(EE_Parameter.Name, "Sport\0", 12);
EE_Parameter.crc = RAM_Checksum((uint8_t*)(&EE_Parameter), sizeof(EE_Parameter)-1);
}
*/
 
/***************************************************/
/* Default Values for parameter set 1 */
/***************************************************/
void ParamSet_DefaultSet1(void) // normal
{
CommonDefaults();
EE_Parameter.Stick_P = 10; // Wert : 1-20
EE_Parameter.Stick_D = 16; // Wert : 0-20
EE_Parameter.StickGier_P = 6; // Wert : 1-20
EE_Parameter.Gyro_P = 90; // Wert : 0-247
EE_Parameter.Gyro_I = 120; // Wert : 0-247
EE_Parameter.Gyro_Gier_P = 90; // Wert : 0-247
EE_Parameter.Gyro_Gier_I = 120; // Wert : 0-247
EE_Parameter.Gyro_Stability = 6; // Wert : 1-8
EE_Parameter.I_Faktor = 32;
EE_Parameter.CouplingYawCorrection = 60;
EE_Parameter.DynamicStability = 75;
memcpy(EE_Parameter.Name, "Fast\0", 12);
EE_Parameter.crc = RAM_Checksum((uint8_t*)(&EE_Parameter), sizeof(EE_Parameter)-1);
}
 
 
/***************************************************/
/* Default Values for parameter set 2 */
/***************************************************/
void ParamSet_DefaultSet2(void) // beginner
{
CommonDefaults();
EE_Parameter.Stick_P = 8; // Wert : 1-20
EE_Parameter.Stick_D = 16; // Wert : 0-20
EE_Parameter.StickGier_P = 6; // Wert : 1-20
EE_Parameter.Gyro_P = 100; // Wert : 0-247
EE_Parameter.Gyro_I = 120; // Wert : 0-247
EE_Parameter.Gyro_Gier_P = 100; // Wert : 0-247
EE_Parameter.Gyro_Gier_I = 120; // Wert : 0-247
EE_Parameter.Gyro_Stability = 6; // Wert : 1-8
EE_Parameter.I_Faktor = 16;
EE_Parameter.CouplingYawCorrection = 70;
EE_Parameter.DynamicStability = 70;
memcpy(EE_Parameter.Name, "Normal\0", 12);
EE_Parameter.crc = RAM_Checksum((uint8_t*)(&EE_Parameter), sizeof(EE_Parameter)-1);
}
 
/***************************************************/
/* Default Values for parameter set 3 */
/***************************************************/
void ParamSet_DefaultSet3(void) // beginner
{
CommonDefaults();
EE_Parameter.Stick_P = 6; // Wert : 1-20
EE_Parameter.Stick_D = 10; // Wert : 0-20
EE_Parameter.StickGier_P = 4; // Wert : 1-20
EE_Parameter.Gyro_P = 100; // Wert : 0-247
EE_Parameter.Gyro_I = 120; // Wert : 0-247
EE_Parameter.Gyro_Gier_P = 100; // Wert : 0-247
EE_Parameter.Gyro_Gier_I = 120; // Wert : 0-247
EE_Parameter.Gyro_Stability = 6; // Wert : 1-8
EE_Parameter.I_Faktor = 16;
EE_Parameter.CouplingYawCorrection = 70;
EE_Parameter.DynamicStability = 70;
memcpy(EE_Parameter.Name, "Easy\0", 12);
EE_Parameter.crc = RAM_Checksum((uint8_t*)(&EE_Parameter), sizeof(EE_Parameter)-1);
}
 
 
/***************************************************/
/* Read Parameter from EEPROM as byte */
/***************************************************/
uint8_t GetParamByte(uint16_t param_id)
{
return eeprom_read_byte((uint8_t*)(EEPROM_ADR_PARAM_BEGIN + param_id));
}
 
/***************************************************/
/* Write Parameter to EEPROM as byte */
/***************************************************/
void SetParamByte(uint16_t param_id, uint8_t value)
{
eeprom_write_byte((uint8_t*)(EEPROM_ADR_PARAM_BEGIN + param_id), value);
}
 
/***************************************************/
/* Read Parameter from EEPROM as word */
/***************************************************/
uint16_t GetParamWord(uint16_t param_id)
{
return eeprom_read_word((uint16_t *)(EEPROM_ADR_PARAM_BEGIN + param_id));
}
 
/***************************************************/
/* Write Parameter to EEPROM as word */
/***************************************************/
void SetParamWord(uint16_t param_id, uint16_t value)
{
eeprom_write_word((uint16_t*)(EEPROM_ADR_PARAM_BEGIN + param_id), value);
}
 
/***************************************************/
/* Read Parameter Set from EEPROM */
/***************************************************/
// number [1..5]
uint8_t ParamSet_ReadFromEEProm(uint8_t setnumber)
{
uint8_t crc;
uint16_t eeaddr;
 
// range the setnumber
if((1 > setnumber) || (setnumber > 5)) setnumber = 3;
 
// calculate eeprom addr
eeaddr = EEPROM_ADR_PARAMSET + PARAMSET_STRUCT_LEN * (setnumber - 1);
 
// calculate checksum from eeprom
crc = EEProm_Checksum(eeaddr, PARAMSET_STRUCT_LEN - 1);
 
// check crc
if(crc != eeprom_read_byte((uint8_t*)(eeaddr + PARAMSET_STRUCT_LEN - 1))) return 0;
 
// check revision
if(eeprom_read_byte((uint8_t*)(eeaddr)) != EEPARAM_REVISION) return 0;
 
// read paramset from eeprom
eeprom_read_block((void *) &EE_Parameter, (void*)(EEPROM_ADR_PARAMSET + PARAMSET_STRUCT_LEN * (setnumber - 1)), PARAMSET_STRUCT_LEN);
LED_Init();
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
LIBFC_HoTT_Clear();
#endif
return 1;
}
 
/***************************************************/
/* Write Parameter Set to EEPROM */
/***************************************************/
// number [1..5]
uint8_t ParamSet_WriteToEEProm(uint8_t setnumber)
{
uint8_t crc;
 
if(EE_Parameter.Revision == EEPARAM_REVISION) // write only the right revision to eeprom
{
if(setnumber > 5) setnumber = 5;
if(setnumber < 1) return 0;
LIBFC_CheckSettings();
if(EE_Parameter.GlobalConfig3 & CFG3_VARIO_FAILSAFE) // check the Setting: Not more than 100% emergency gas
{
if(EE_Parameter.NotGas > 99) EE_Parameter.NotGas = 80; // i.e. 80% of Hovergas
}
// update checksum
EE_Parameter.crc = RAM_Checksum((uint8_t*)(&EE_Parameter), sizeof(EE_Parameter)-1);
 
// write paramset to eeprom
eeprom_write_block((void *) &EE_Parameter, (void*)(EEPROM_ADR_PARAMSET + PARAMSET_STRUCT_LEN * (setnumber - 1)), PARAMSET_STRUCT_LEN);
 
// backup channel settings to separate block in eeprom
eeprom_write_block( (void*)(EE_Parameter.Kanalbelegung), (void*)(EEPROM_ADR_CHANNELS), sizeof(EE_Parameter.Kanalbelegung));
 
// write crc of channel block to eeprom
crc = RAM_Checksum((uint8_t*)(EE_Parameter.Kanalbelegung), sizeof(EE_Parameter.Kanalbelegung));
eeprom_write_byte((uint8_t*)(EEPROM_ADR_CHANNELS + sizeof(EE_Parameter.Kanalbelegung)), crc);
 
// update active settings number
SetActiveParamSet(setnumber);
LED_Init();
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
LIBFC_HoTT_Clear();
#endif
return 1;
}
// wrong revision
return 0;
}
 
/***************************************************/
/* Read MixerTable from EEPROM */
/***************************************************/
uint8_t MixerTable_ReadFromEEProm(void)
{
uint8_t crc;
 
// calculate checksum in eeprom
crc = EEProm_Checksum(EEPROM_ADR_MIXERTABLE, sizeof(Mixer) - 1);
 
// check crc
if( crc != eeprom_read_byte((uint8_t*)(EEPROM_ADR_MIXERTABLE + sizeof(Mixer) - 1)) ) return 0;
 
// check revision
if(eeprom_read_byte((uint8_t*)(EEPROM_ADR_MIXERTABLE)) != EEMIXER_REVISION) return 0;
 
// read mixer table
eeprom_read_block((void *) &Mixer, (void*)(EEPROM_ADR_MIXERTABLE), sizeof(Mixer));
return 1;
}
 
/***************************************************/
/* Write Mixer Table to EEPROM */
/***************************************************/
uint8_t MixerTable_WriteToEEProm(void)
{
if(Mixer.Revision == EEMIXER_REVISION)
{
// update crc
Mixer.crc = RAM_Checksum((uint8_t*)(&Mixer), sizeof(Mixer) - 1);
 
// write to eeprom
eeprom_write_block((void *) &Mixer, (void*)(EEPROM_ADR_MIXERTABLE), sizeof(Mixer));
return 1;
}
else return 0;
}
 
/***************************************************/
/* Default Values for Mixer Table */
/***************************************************/
void MixerTable_Default(void) // Quadro
{
uint8_t i;
 
Mixer.Revision = EEMIXER_REVISION;
// clear mixer table
for(i = 0; i < 16; i++)
{
Mixer.Motor[i][MIX_GAS] = 0;
Mixer.Motor[i][MIX_NICK] = 0;
Mixer.Motor[i][MIX_ROLL] = 0;
Mixer.Motor[i][MIX_YAW] = 0;
}
// default = Quadro
Mixer.Motor[0][MIX_GAS] = 64; Mixer.Motor[0][MIX_NICK] = +64; Mixer.Motor[0][MIX_ROLL] = 0; Mixer.Motor[0][MIX_YAW] = +64;
Mixer.Motor[1][MIX_GAS] = 64; Mixer.Motor[1][MIX_NICK] = -64; Mixer.Motor[1][MIX_ROLL] = 0; Mixer.Motor[1][MIX_YAW] = +64;
Mixer.Motor[2][MIX_GAS] = 64; Mixer.Motor[2][MIX_NICK] = 0; Mixer.Motor[2][MIX_ROLL] = -64; Mixer.Motor[2][MIX_YAW] = -64;
Mixer.Motor[3][MIX_GAS] = 64; Mixer.Motor[3][MIX_NICK] = 0; Mixer.Motor[3][MIX_ROLL] = +64; Mixer.Motor[3][MIX_YAW] = -64;
memcpy(Mixer.Name, "Quadro\0", 7);
Mixer.crc = RAM_Checksum((uint8_t*)(&Mixer), sizeof(Mixer) - 1);
}
 
/***************************************************/
/* Get active parameter set */
/***************************************************/
uint8_t GetActiveParamSet(void)
{
uint8_t setnumber;
setnumber = eeprom_read_byte((uint8_t*)(EEPROM_ADR_PARAM_BEGIN + PID_ACTIVE_SET));
if(setnumber > 5)
{
setnumber = 3;
eeprom_write_byte((void*)(EEPROM_ADR_PARAM_BEGIN+PID_ACTIVE_SET), setnumber);
}
return(setnumber);
}
 
/***************************************************/
/* Set active parameter set */
/***************************************************/
void SetActiveParamSet(uint8_t setnumber)
{
if(setnumber > 5) setnumber = 5;
if(setnumber < 1) setnumber = 1;
eeprom_write_byte((uint8_t*)(EEPROM_ADR_PARAM_BEGIN + PID_ACTIVE_SET), setnumber);
}
 
/***************************************************/
/* Set default parameter set */
/***************************************************/
void SetDefaultParameter(uint8_t set, uint8_t restore_channels)
{
 
if(set > 5) set = 5;
else if(set < 1) set = 1;
 
switch(set)
{
case 1:
ParamSet_DefaultSet1(); // Fill ParamSet Structure to default parameter set 1 (Sport)
break;
case 2:
ParamSet_DefaultSet2(); // Kamera
break;
case 3:
ParamSet_DefaultSet3(); // Beginner
break;
default:
ParamSet_DefaultSet3(); // Beginner
break;
}
if(restore_channels)
{
uint8_t crc;
// 1st check for a valid channel backup in eeprom
crc = EEProm_Checksum(EEPROM_ADR_CHANNELS, sizeof(EE_Parameter.Kanalbelegung));
if(crc == eeprom_read_byte((uint8_t*)(EEPROM_ADR_CHANNELS + sizeof(EE_Parameter.Kanalbelegung))) )
{
eeprom_read_block((void *)EE_Parameter.Kanalbelegung, (void*)(EEPROM_ADR_CHANNELS), sizeof(EE_Parameter.Kanalbelegung));
}
else ParamSet_DefaultStickMapping();
}
else ParamSet_DefaultStickMapping();
ParamSet_WriteToEEProm(set);
}
 
/***************************************************/
/* Initialize EEPROM Parameter Sets */
/***************************************************/
void ParamSet_Init(void)
{
uint8_t channel_backup = 0, bad_params = 0, ee_default = 0,i;
 
 
if(EEPARAM_REVISION != GetParamByte(PID_EE_REVISION) )
{
ee_default = 1; // software update or forced by mktool
}
 
 
// 1st check for a valid channel backup in eeprom
i = EEProm_Checksum(EEPROM_ADR_CHANNELS, sizeof(EE_Parameter.Kanalbelegung));
if(i == eeprom_read_byte((uint8_t*)(EEPROM_ADR_CHANNELS + sizeof(EE_Parameter.Kanalbelegung))) ) channel_backup = 1;
 
 
// parameter check
 
// check all 5 parameter settings
for (i = 1;i < 6; i++)
{
if(ee_default || !ParamSet_ReadFromEEProm(i)) // could not read paramset from eeprom
{
bad_params = 1;
printf("\n\rGenerating default Parm Set %d",i);
switch(i)
{
case 1:
ParamSet_DefaultSet1(); // Fill ParamSet Structure to default parameter set 1 (Sport)
break;
case 2:
ParamSet_DefaultSet2(); // Kamera
break;
case 3:
ParamSet_DefaultSet3(); // Beginner
break;
default:
ParamSet_DefaultSet3(); // Kamera
break;
}
if(channel_backup) // if we have an channel mapping backup in eeprom
{ // restore it from eeprom
eeprom_read_block((void *)EE_Parameter.Kanalbelegung, (void*)(EEPROM_ADR_CHANNELS), sizeof(EE_Parameter.Kanalbelegung));
}
else
{ // use default mapping
ParamSet_DefaultStickMapping();
}
ParamSet_WriteToEEProm(i);
}
}
if(bad_params) // at least one of the parameter settings were invalid
{
// default-Setting is parameter set 3
SetActiveParamSet(3);
}
 
 
// read active parameter set to ParamSet stucture
i = GetActiveParamSet();
ParamSet_ReadFromEEProm(i);
printf("\n\rUsing Parm Set %d", i);
 
// load mixer table
if(GetParamByte(PID_EE_REVISION) == 0xff || !MixerTable_ReadFromEEProm() )
{
printf("\n\rGenerating default Mixer Table");
MixerTable_Default(); // Quadro
MixerTable_WriteToEEProm();
}
if(ee_default) SetParamByte(PID_EE_REVISION, EEPARAM_REVISION);
// determine motornumber
RequiredMotors = 0;
for(i = 0; i < 16; i++)
{
if(Mixer.Motor[i][MIX_GAS] > 0) RequiredMotors++;
}
 
printf("\n\rMixer-Config: '%s' (%u Motors)",Mixer.Name, RequiredMotors);
PrintLine();// ("\n\r===================================");
 
}
/branches/V0.88n S.BUS ATmega644 tempolo/fc.c
0,0 → 1,1907
/*#######################################################################################
Flight Control
#######################################################################################*/
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + www.MikroKopter.com
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Software Nutzungsbedingungen (english version: see below)
// + der Fa. HiSystems GmbH, Flachsmeerstrasse 2, 26802 Moormerland - nachfolgend Lizenzgeber genannt -
// + Der Lizenzgeber räumt dem Kunden ein nicht-ausschließliches, zeitlich und räumlich* unbeschränktes Recht ein, die im den
// + Mikrocontroller verwendete Firmware für die Hardware Flight-Ctrl, Navi-Ctrl, BL-Ctrl, MK3Mag & PC-Programm MikroKopter-Tool
// + - nachfolgend Software genannt - nur für private Zwecke zu nutzen.
// + Der Einsatz dieser Software ist nur auf oder mit Produkten des Lizenzgebers zulässig.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Die vom Lizenzgeber gelieferte Software ist urheberrechtlich geschützt. Alle Rechte an der Software sowie an sonstigen im
// + Rahmen der Vertragsanbahnung und Vertragsdurchführung überlassenen Unterlagen stehen im Verhältnis der Vertragspartner ausschließlich dem Lizenzgeber zu.
// + Die in der Software enthaltenen Copyright-Vermerke, Markenzeichen, andere Rechtsvorbehalte, Seriennummern sowie
// + sonstige der Programmidentifikation dienenden Merkmale dürfen vom Kunden nicht verändert oder unkenntlich gemacht werden.
// + Der Kunde trifft angemessene Vorkehrungen für den sicheren Einsatz der Software. Er wird die Software gründlich auf deren
// + Verwendbarkeit zu dem von ihm beabsichtigten Zweck testen, bevor er diese operativ einsetzt.
// + Die Haftung des Lizenzgebers wird - soweit gesetzlich zulässig - begrenzt in Höhe des typischen und vorhersehbaren
// + Schadens. Die gesetzliche Haftung bei Personenschäden und nach dem Produkthaftungsgesetz bleibt unberührt. Dem Lizenzgeber steht jedoch der Einwand
// + des Mitverschuldens offen.
// + Der Kunde trifft angemessene Vorkehrungen für den Fall, dass die Software ganz oder teilweise nicht ordnungsgemäß arbeitet.
// + Er wird die Software gründlich auf deren Verwendbarkeit zu dem von ihm beabsichtigten Zweck testen, bevor er diese operativ einsetzt.
// + Der Kunde wird er seine Daten vor Einsatz der Software nach dem Stand der Technik sichern.
// + Der Kunde ist darüber unterrichtet, dass der Lizenzgeber seine Daten im zur Vertragsdurchführung erforderlichen Umfang
// + und auf Grundlage der Datenschutzvorschriften erhebt, speichert, verarbeitet und, sofern notwendig, an Dritte übermittelt.
// + *) Die räumliche Nutzung bezieht sich nur auf den Einsatzort, nicht auf die Reichweite der programmierten Software.
// + #### ENDE DER NUTZUNGSBEDINGUNGEN ####'
// + Hinweis: Informationen über erweiterte Nutzungsrechte (wie z.B. Nutzung für nicht-private Zwecke) sind auf Anfrage per Email an info(@)hisystems.de verfügbar.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Software LICENSING TERMS
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + of HiSystems GmbH, Flachsmeerstrasse 2, 26802 Moormerland, Germany - the Licensor -
// + The Licensor grants the customer a non-exclusive license to use the microcontroller firmware of the Flight-Ctrl, Navi-Ctrl, BL-Ctrl, and MK3Mag hardware
// + (the Software) exclusively for private purposes. The License is unrestricted with respect to time and territory*.
// + The Software may only be used with the Licensor's products.
// + The Software provided by the Licensor is protected by copyright. With respect to the relationship between the parties to this
// + agreement, all rights pertaining to the Software and other documents provided during the preparation and execution of this
// + agreement shall be the property of the Licensor.
// + The information contained in the Software copyright notices, trademarks, other legal reservations, serial numbers and other
// + features that can be used to identify the program may not be altered or defaced by the customer.
// + The customer shall be responsible for taking reasonable precautions
// + for the safe use of the Software. The customer shall test the Software thoroughly regarding its suitability for the
// + intended purpose before implementing it for actual operation. The Licensor's liability shall be limited to the extent of typical and
// + foreseeable damage to the extent permitted by law, notwithstanding statutory liability for bodily injury and product
// + liability. However, the Licensor shall be entitled to the defense of contributory negligence.
// + The customer will take adequate precautions in the case, that the software is not working properly. The customer will test
// + the software for his purpose before any operational usage. The customer will backup his data before using the software.
// + The customer understands that the Licensor collects, stores and processes, and, where required, forwards, customer data
// + to third parties to the extent necessary for executing the agreement, subject to applicable data protection and privacy regulations.
// + *) The territory aspect only refers to the place where the Software is used, not its programmed range.
// + #### END OF LICENSING TERMS ####
// + Note: For information on license extensions (e.g. commercial use), please contact us at info(@)hisystems.de.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 
#include "main.h"
#include "mymath.h"
#include "isqrt.h"
 
unsigned char h,m,s;
unsigned int BaroExpandActive = 0;
int MesswertNick,MesswertRoll,MesswertGier,MesswertGierBias, RohMesswertNick,RohMesswertRoll;
int TrimNick, TrimRoll;
int AdNeutralNick = 0,AdNeutralRoll = 0,AdNeutralGier = 0,StartNeutralRoll = 0,StartNeutralNick = 0;
int Mittelwert_AccNick, Mittelwert_AccRoll;
unsigned int NeutralAccX=0, NeutralAccY=0;
int NaviAccNick, NaviAccRoll,NaviCntAcc = 0;
int NeutralAccZ = 0;
unsigned char ControlHeading = 0;// in 2°
long IntegralNick = 0,IntegralNick2 = 0;
long IntegralRoll = 0,IntegralRoll2 = 0;
long IntegralAccNick = 0,IntegralAccRoll = 0,IntegralAccZ = 0;
long Integral_Gier = 0;
long Mess_IntegralNick = 0,Mess_IntegralNick2 = 0;
long Mess_IntegralRoll = 0,Mess_IntegralRoll2 = 0;
long Mess_Integral_Gier = 0,Mess_Integral_Gier2 = 0;
long MittelIntegralNick,MittelIntegralRoll,MittelIntegralNick2,MittelIntegralRoll2;
long SummeNick=0,SummeRoll=0;
volatile long Mess_Integral_Hoch = 0;
int KompassValue = -1;
int KompassSollWert = 0;
//int KompassRichtung = 0;
char CalculateCompassTimer = 100;
unsigned char KompassFusion = 32;
unsigned int KompassSignalSchlecht = 50;
unsigned char MAX_GAS,MIN_GAS;
unsigned char HoehenReglerAktiv = 0;
unsigned char TrichterFlug = 0;
long Umschlag180Nick = 250000L, Umschlag180Roll = 250000L;
long ErsatzKompass;
int ErsatzKompassInGrad; // Kompasswert in Grad
int GierGyroFehler = 0;
char GyroFaktor,GyroFaktorGier;
char IntegralFaktor,IntegralFaktorGier;
int DiffNick,DiffRoll;
int StickGasHover = 120, HoverGasMin = 0, HoverGasMax = 1023;
int StickNick = 0,StickRoll = 0,StickGier = 0,StickGas = 0;
//int Poti1 = 0, Poti2 = 0, Poti3 = 0, Poti4 = 0, Poti5 = 0, Poti6 = 0, Poti7 = 0, Poti8 = 0;
unsigned char Poti[9] = {0,0,0,0,0,0,0,0};
volatile unsigned char SenderOkay = 0;
char MotorenEin = 0,StartTrigger = 0;
long HoehenWert = 0;
long SollHoehe = 0;
signed int AltitudeSetpointTrimming = 0;
long FromNC_AltitudeSetpoint = 0;
unsigned char FromNC_AltitudeSpeed = 0;
unsigned char carefree_old = 50; // to make the Beep when switching
signed char WaypointTrimming = 0;
int CompassGierSetpoint = 0;
unsigned char CalibrationDone = 0;
char NeueKompassRichtungMerken = 0;
int LageKorrekturRoll = 0,LageKorrekturNick = 0, HoverGas = 0;
//float Ki = FAKTOR_I;
int Ki = 10300 / 33;
unsigned char Looping_Nick = 0,Looping_Roll = 0;
unsigned char Looping_Links = 0, Looping_Rechts = 0, Looping_Unten = 0, Looping_Oben = 0;
 
unsigned char Parameter_Luftdruck_D = 48; // Wert : 0-250
unsigned char Parameter_HoehenSchalter = 251; // Wert : 0-250
unsigned char Parameter_Hoehe_P = 16; // Wert : 0-32
unsigned char Parameter_Hoehe_ACC_Wirkung = 58; // Wert : 0-250
unsigned char Parameter_KompassWirkung = 64; // Wert : 0-250
unsigned char Parameter_Hoehe_GPS_Z = 64; // Wert : 0-250
unsigned char Parameter_Gyro_D = 8; // Wert : 0-250
unsigned char Parameter_Gyro_P = 150; // Wert : 10-250
unsigned char Parameter_Gyro_I = 150; // Wert : 0-250
unsigned char Parameter_Gyro_Gier_P = 150; // Wert : 10-250
unsigned char Parameter_Gyro_Gier_I = 150; // Wert : 10-250
unsigned char Parameter_Gier_P = 2; // Wert : 1-20
unsigned char Parameter_I_Faktor = 10; // Wert : 1-20
unsigned char Parameter_UserParam1 = 0;
unsigned char Parameter_UserParam2 = 0;
unsigned char Parameter_UserParam3 = 0;
unsigned char Parameter_UserParam4 = 0;
unsigned char Parameter_UserParam5 = 0;
unsigned char Parameter_UserParam6 = 0;
unsigned char Parameter_UserParam7 = 0;
unsigned char Parameter_UserParam8 = 0;
unsigned char Parameter_ServoNickControl = 100;
unsigned char Parameter_ServoRollControl = 100;
unsigned char Parameter_LoopGasLimit = 70;
unsigned char Parameter_AchsKopplung1 = 90;
unsigned char Parameter_AchsKopplung2 = 65;
unsigned char Parameter_CouplingYawCorrection = 64;
//unsigned char Parameter_AchsGegenKopplung1 = 0;
unsigned char Parameter_DynamicStability = 100;
unsigned char Parameter_J16Bitmask; // for the J16 Output
unsigned char Parameter_J16Timing; // for the J16 Output
unsigned char Parameter_J17Bitmask; // for the J17 Output
unsigned char Parameter_J17Timing; // for the J17 Output
unsigned char Parameter_NaviGpsModeControl; // Parameters for the Naviboard
unsigned char Parameter_NaviGpsGain;
unsigned char Parameter_NaviGpsP;
unsigned char Parameter_NaviGpsI;
unsigned char Parameter_NaviGpsD;
unsigned char Parameter_NaviGpsACC;
unsigned char Parameter_NaviOperatingRadius;
unsigned char Parameter_NaviWindCorrection;
unsigned char Parameter_NaviSpeedCompensation;
unsigned char Parameter_ExternalControl;
unsigned char Parameter_GlobalConfig;
unsigned char Parameter_ExtraConfig;
unsigned char Parameter_MaximumAltitude;
unsigned char Parameter_Servo3,Parameter_Servo4,Parameter_Servo5;
unsigned char CareFree = 0;
const signed char sintab[31] = { 0, 2, 4, 6, 7, 8, 8, 8, 7, 6, 4, 2, 0, -2, -4, -6, -7, -8, -8, -8, -7, -6, -4, -2, 0, 2, 4, 6, 7, 8, 8}; // 15° steps
 
signed int ExternStickNick = 0,ExternStickRoll = 0,ExternStickGier = 0, ExternHoehenValue = -20;
int MaxStickNick = 0,MaxStickRoll = 0;
unsigned int modell_fliegt = 0;
volatile unsigned char FC_StatusFlags = 0, FC_StatusFlags2 = 0;
long GIER_GRAD_FAKTOR = 1291;
signed int KopplungsteilNickRoll,KopplungsteilRollNick;
signed int tmp_motorwert[MAX_MOTORS];
char VarioCharacter = ' ';
unsigned int HooverGasEmergencyPercent = 0; // The gas value for Emergency landing
 
#define LIMIT_MIN(value, min) {if(value <= min) value = min;}
#define LIMIT_MAX(value, max) {if(value >= max) value = max;}
#define LIMIT_MIN_MAX(value, min, max) {if(value <= min) value = min; else if(value >= max) value = max;}
 
 
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Debugwerte zuordnen
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void CopyDebugValues(void)
{
DebugOut.Analog[0] = IntegralNick / (EE_Parameter.GyroAccFaktor * 4);
DebugOut.Analog[1] = IntegralRoll / (EE_Parameter.GyroAccFaktor * 4);
DebugOut.Analog[2] = Mittelwert_AccNick / 4;
DebugOut.Analog[3] = Mittelwert_AccRoll / 4;
DebugOut.Analog[4] = (signed int) AdNeutralGier - AdWertGier;
DebugOut.Analog[5] = HoehenWert/5;
DebugOut.Analog[6] = AdWertAccHoch;//(Mess_Integral_Hoch / 512);// Aktuell_az;
DebugOut.Analog[8] = KompassValue;
DebugOut.Analog[9] = UBat;
DebugOut.Analog[10] = SenderOkay;
DebugOut.Analog[11] = ErsatzKompassInGrad;
DebugOut.Analog[12] = Motor[0].SetPoint;
DebugOut.Analog[13] = Motor[1].SetPoint;
DebugOut.Analog[14] = Motor[2].SetPoint;
DebugOut.Analog[15] = Motor[3].SetPoint;
DebugOut.Analog[20] = ServoNickValue;
DebugOut.Analog[22] = Capacity.ActualCurrent;
DebugOut.Analog[23] = Capacity.UsedCapacity;
DebugOut.Analog[24] = SollHoehe/5;
// DebugOut.Analog[22] = FromNaviCtrl_Value.GpsZ;
// DebugOut.Analog[29] = FromNaviCtrl_Value.SerialDataOkay;
DebugOut.Analog[27] = KompassSollWert;
DebugOut.Analog[29] = Capacity.MinOfMaxPWM;
DebugOut.Analog[30] = GPS_Nick;
DebugOut.Analog[31] = GPS_Roll;
if(VersionInfo.HardwareError[0] || VersionInfo.HardwareError[1]) DebugOut.Status[1] |= 1; else DebugOut.Status[1] &= 0xfe;
}
 
 
 
void Piep(unsigned char Anzahl, unsigned int dauer)
{
if(MotorenEin) return; //auf keinen Fall im Flug!
GRN_OFF;
while(Anzahl--)
{
beeptime = dauer;
while(beeptime);
Delay_ms(dauer * 2);
}
GRN_ON;
}
 
//############################################################################
// Messwerte beim Ermitteln der Nullage
void CalibrierMittelwert(void)
//############################################################################
{
unsigned char i;
if(PlatinenVersion == 13) SucheGyroOffset();
// ADC auschalten, damit die Werte sich nicht während der Berechnung ändern
ANALOG_OFF;
MesswertNick = AdWertNick;
MesswertRoll = AdWertRoll;
MesswertGier = AdWertGier;
Mittelwert_AccNick = ACC_AMPLIFY * AdWertAccNick;
Mittelwert_AccRoll = ACC_AMPLIFY * AdWertAccRoll;
// ADC einschalten
ANALOG_ON;
for(i=0;i<8;i++)
{
int tmp;
tmp = PPM_in[EE_Parameter.Kanalbelegung[K_POTI1 + i]] + 127;
LIMIT_MIN_MAX(tmp, 0, 255);
if(Poti[i] > tmp) Poti[i]--; else if(Poti[i] < tmp) Poti[i]++;
}
Umschlag180Nick = (long) EE_Parameter.WinkelUmschlagNick * 2500L;
Umschlag180Roll = (long) EE_Parameter.WinkelUmschlagRoll * 2500L;
}
 
//############################################################################
// Nullwerte ermitteln
void SetNeutral(unsigned char AccAdjustment)
//############################################################################
{
unsigned char i;
unsigned int gier_neutral=0, nick_neutral=0, roll_neutral=0;
VersionInfo.HardwareError[0] = 0;
// HEF4017Reset_ON;
NeutralAccX = 0;
NeutralAccY = 0;
NeutralAccZ = 0;
 
AdNeutralNick = 0;
AdNeutralRoll = 0;
AdNeutralGier = 0;
 
Parameter_AchsKopplung1 = 0;
Parameter_AchsKopplung2 = 0;
 
ExpandBaro = 0;
 
CalibrierMittelwert();
Delay_ms_Mess(100);
 
CalibrierMittelwert();
 
if((EE_Parameter.GlobalConfig & CFG_HOEHENREGELUNG)) // Höhenregelung aktiviert?
{
if((MessLuftdruck > 950) || (MessLuftdruck < 750)) SucheLuftruckOffset();
}
#define NEUTRAL_FILTER 32
for(i=0; i<NEUTRAL_FILTER; i++)
{
Delay_ms_Mess(10);
gier_neutral += AdWertGier;
nick_neutral += AdWertNick;
roll_neutral += AdWertRoll;
}
AdNeutralNick= (nick_neutral+NEUTRAL_FILTER/2) / (NEUTRAL_FILTER / 8);
AdNeutralRoll= (roll_neutral+NEUTRAL_FILTER/2) / (NEUTRAL_FILTER / 8);
AdNeutralGier= (gier_neutral+NEUTRAL_FILTER/2) / (NEUTRAL_FILTER);
 
StartNeutralRoll = AdNeutralRoll;
StartNeutralNick = AdNeutralNick;
 
if(AccAdjustment)
{
NeutralAccX = abs(Mittelwert_AccNick) / (2*ACC_AMPLIFY);
NeutralAccY = abs(Mittelwert_AccRoll) / (2*ACC_AMPLIFY);
NeutralAccZ = Aktuell_az;
 
// Save ACC neutral settings to eeprom
SetParamWord(PID_ACC_NICK, (uint16_t)NeutralAccX);
SetParamWord(PID_ACC_ROLL, (uint16_t)NeutralAccY);
SetParamWord(PID_ACC_TOP, (uint16_t)NeutralAccZ);
}
else
{
// restore from eeprom
NeutralAccX = (int16_t)GetParamWord(PID_ACC_NICK);
NeutralAccY = (int16_t)GetParamWord(PID_ACC_ROLL);
NeutralAccZ = (int16_t)GetParamWord(PID_ACC_TOP);
// strange settings?
if(((unsigned int) NeutralAccX > 2048) || ((unsigned int) NeutralAccY > 2048) || ((unsigned int) NeutralAccZ > 1024))
{
printf("\n\rACC not calibrated!\r\n");
NeutralAccX = abs(Mittelwert_AccNick) / (2*ACC_AMPLIFY);
NeutralAccY = abs(Mittelwert_AccRoll) / (2*ACC_AMPLIFY);
NeutralAccZ = Aktuell_az;
}
}
 
MesswertNick = 0;
MesswertRoll = 0;
MesswertGier = 0;
Delay_ms_Mess(100);
Mittelwert_AccNick = ACC_AMPLIFY * AdWertAccNick;
Mittelwert_AccRoll = ACC_AMPLIFY * AdWertAccRoll;
IntegralNick = EE_Parameter.GyroAccFaktor * (long)Mittelwert_AccNick;
IntegralRoll = EE_Parameter.GyroAccFaktor * (long)Mittelwert_AccRoll;
Mess_IntegralNick = IntegralNick;
Mess_IntegralRoll = IntegralRoll;
Mess_Integral_Gier = 0;
StartLuftdruck = Luftdruck;
VarioMeter = 0;
Mess_Integral_Hoch = 0;
KompassSollWert = KompassValue;
KompassSignalSchlecht = 100;
beeptime = 50;
Umschlag180Nick = ((long) EE_Parameter.WinkelUmschlagNick * 2500L) + 15000L;
Umschlag180Roll = ((long) EE_Parameter.WinkelUmschlagRoll * 2500L) + 15000L;
ExternHoehenValue = 0;
ErsatzKompass = KompassValue * GIER_GRAD_FAKTOR;
GierGyroFehler = 0;
LED_Init();
FC_StatusFlags |= FC_STATUS_CALIBRATE;
FromNaviCtrl_Value.Kalman_K = -1;
FromNaviCtrl_Value.Kalman_MaxDrift = 0;
FromNaviCtrl_Value.Kalman_MaxFusion = 32;
for(i=0;i<8;i++)
{
Poti[i] = PPM_in[EE_Parameter.Kanalbelegung[K_POTI1 + i]] + 127;
}
SenderOkay = 100;
if(ServoActive)
{
// HEF4017Reset_ON;
DDRD |=0x80; // enable J7 -> Servo signal
}
 
if((AdNeutralNick < 150 * 16) || (AdNeutralNick > 850 * 16)) { VersionInfo.HardwareError[0] |= FC_ERROR0_GYRO_NICK; };
if((AdNeutralRoll < 150 * 16) || (AdNeutralRoll > 850 * 16)) { VersionInfo.HardwareError[0] |= FC_ERROR0_GYRO_ROLL; };
if((AdNeutralGier < 150 * 2) || (AdNeutralGier > 850 * 2)) { VersionInfo.HardwareError[0] |= FC_ERROR0_GYRO_YAW; };
if((NeutralAccX < 300) || (NeutralAccX > 750)) { VersionInfo.HardwareError[0] |= FC_ERROR0_ACC_NICK; };
if((NeutralAccY < 300) || (NeutralAccY > 750)) { VersionInfo.HardwareError[0] |= FC_ERROR0_ACC_ROLL; };
if((NeutralAccZ < 512) || (NeutralAccZ > 850)) { VersionInfo.HardwareError[0] |= FC_ERROR0_ACC_TOP; };
carefree_old = 70;
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
LIBFC_HoTT_Clear();
#endif
}
 
 
//############################################################################
// Bearbeitet die Messwerte
void Mittelwert(void)
//############################################################################
{
static signed long tmpl,tmpl2,tmpl3,tmpl4;
static signed int oldNick, oldRoll, d2Roll, d2Nick;
signed long winkel_nick, winkel_roll;
MesswertGier = (signed int) AdNeutralGier - AdWertGier;
MesswertNick = (signed int) AdWertNickFilter / 8;
MesswertRoll = (signed int) AdWertRollFilter / 8;
RohMesswertNick = MesswertNick;
RohMesswertRoll = MesswertRoll;
 
// Beschleunigungssensor ++++++++++++++++++++++++++++++++++++++++++++++++
Mittelwert_AccNick = (Mittelwert_AccNick * 3 + ((ACC_AMPLIFY * AdWertAccNick))) / 4L;
Mittelwert_AccRoll = (Mittelwert_AccRoll * 3 + ((ACC_AMPLIFY * AdWertAccRoll))) / 4L;
IntegralAccNick += ACC_AMPLIFY * AdWertAccNick;
IntegralAccRoll += ACC_AMPLIFY * AdWertAccRoll;
NaviAccNick += AdWertAccNick;
NaviAccRoll += AdWertAccRoll;
NaviCntAcc++;
IntegralAccZ += Aktuell_az - NeutralAccZ;
 
//++++++++++++++++++++++++++++++++++++++++++++++++
// ADC einschalten
ANALOG_ON;
AdReady = 0;
//++++++++++++++++++++++++++++++++++++++++++++++++
 
if(Mess_IntegralRoll > 93000L) winkel_roll = 93000L;
else if(Mess_IntegralRoll <-93000L) winkel_roll = -93000L;
else winkel_roll = Mess_IntegralRoll;
 
if(Mess_IntegralNick > 93000L) winkel_nick = 93000L;
else if(Mess_IntegralNick <-93000L) winkel_nick = -93000L;
else winkel_nick = Mess_IntegralNick;
 
// Gier ++++++++++++++++++++++++++++++++++++++++++++++++
Mess_Integral_Gier += MesswertGier;
ErsatzKompass += MesswertGier;
// Kopplungsanteil +++++++++++++++++++++++++++++++++++++
if(!Looping_Nick && !Looping_Roll && (Parameter_GlobalConfig & CFG_ACHSENKOPPLUNG_AKTIV))
{
tmpl3 = (MesswertRoll * winkel_nick) / 2048L;
tmpl3 *= Parameter_AchsKopplung2; //65
tmpl3 /= 4096L;
tmpl4 = (MesswertNick * winkel_roll) / 2048L;
tmpl4 *= Parameter_AchsKopplung2; //65
tmpl4 /= 4096L;
KopplungsteilNickRoll = tmpl3;
KopplungsteilRollNick = tmpl4;
tmpl4 -= tmpl3;
ErsatzKompass += tmpl4;
if(!Parameter_CouplingYawCorrection) Mess_Integral_Gier -= tmpl4/2; // Gier nachhelfen
 
tmpl = ((MesswertGier + tmpl4) * winkel_nick) / 2048L;
tmpl *= Parameter_AchsKopplung1; // 90
tmpl /= 4096L;
tmpl2 = ((MesswertGier + tmpl4) * winkel_roll) / 2048L;
tmpl2 *= Parameter_AchsKopplung1;
tmpl2 /= 4096L;
if(abs(MesswertGier) > 64) if(labs(tmpl) > 128 || labs(tmpl2) > 128) TrichterFlug = 1;
//MesswertGier += (Parameter_CouplingYawCorrection * tmpl4) / 256;
}
else tmpl = tmpl2 = KopplungsteilNickRoll = KopplungsteilRollNick = 0;
TrimRoll = tmpl - tmpl2 / 100L;
TrimNick = -tmpl2 + tmpl / 100L;
// Kompasswert begrenzen ++++++++++++++++++++++++++++++++++++++++++++++++
if(ErsatzKompass >= (360L * GIER_GRAD_FAKTOR)) ErsatzKompass -= 360L * GIER_GRAD_FAKTOR; // 360° Umschlag
if(ErsatzKompass < 0) ErsatzKompass += 360L * GIER_GRAD_FAKTOR;
// Roll ++++++++++++++++++++++++++++++++++++++++++++++++
Mess_IntegralRoll2 += MesswertRoll + TrimRoll;
Mess_IntegralRoll += MesswertRoll + TrimRoll - LageKorrekturRoll;
if(Mess_IntegralRoll > Umschlag180Roll)
{
Mess_IntegralRoll = -(Umschlag180Roll - 25000L);
Mess_IntegralRoll2 = Mess_IntegralRoll;
}
if(Mess_IntegralRoll <-Umschlag180Roll)
{
Mess_IntegralRoll = (Umschlag180Roll - 25000L);
Mess_IntegralRoll2 = Mess_IntegralRoll;
}
// Nick ++++++++++++++++++++++++++++++++++++++++++++++++
Mess_IntegralNick2 += MesswertNick + TrimNick;
Mess_IntegralNick += MesswertNick + TrimNick - LageKorrekturNick;
if(Mess_IntegralNick > Umschlag180Nick)
{
Mess_IntegralNick = -(Umschlag180Nick - 25000L);
Mess_IntegralNick2 = Mess_IntegralNick;
}
if(Mess_IntegralNick <-Umschlag180Nick)
{
Mess_IntegralNick = (Umschlag180Nick - 25000L);
Mess_IntegralNick2 = Mess_IntegralNick;
}
 
Integral_Gier = Mess_Integral_Gier;
IntegralNick = Mess_IntegralNick;
IntegralRoll = Mess_IntegralRoll;
IntegralNick2 = Mess_IntegralNick2;
IntegralRoll2 = Mess_IntegralRoll2;
 
#define D_LIMIT 128
 
MesswertNick = HiResNick / 8;
MesswertRoll = HiResRoll / 8;
 
if(AdWertNick < 15) MesswertNick = -1000; if(AdWertNick < 7) MesswertNick = -2000;
if(PlatinenVersion == 10) { if(AdWertNick > 1010) MesswertNick = +1000; if(AdWertNick > 1017) MesswertNick = +2000; }
else { if(AdWertNick > 2000) MesswertNick = +1000; if(AdWertNick > 2015) MesswertNick = +2000; }
if(AdWertRoll < 15) MesswertRoll = -1000; if(AdWertRoll < 7) MesswertRoll = -2000;
if(PlatinenVersion == 10) { if(AdWertRoll > 1010) MesswertRoll = +1000; if(AdWertRoll > 1017) MesswertRoll = +2000; }
else { if(AdWertRoll > 2000) MesswertRoll = +1000; if(AdWertRoll > 2015) MesswertRoll = +2000; }
 
if(Parameter_Gyro_D)
{
d2Nick = HiResNick - oldNick;
oldNick = (oldNick + HiResNick)/2;
if(d2Nick > D_LIMIT) d2Nick = D_LIMIT;
else if(d2Nick < -D_LIMIT) d2Nick = -D_LIMIT;
 
d2Roll = HiResRoll - oldRoll;
oldRoll = (oldRoll + HiResRoll)/2;
if(d2Roll > D_LIMIT) d2Roll = D_LIMIT;
else if(d2Roll < -D_LIMIT) d2Roll = -D_LIMIT;
 
MesswertNick += (d2Nick * (signed int) Parameter_Gyro_D) / 16;
MesswertRoll += (d2Roll * (signed int) Parameter_Gyro_D) / 16;
HiResNick += (d2Nick * (signed int) Parameter_Gyro_D);
HiResRoll += (d2Roll * (signed int) Parameter_Gyro_D);
}
 
if(RohMesswertRoll > 0) TrimRoll += ((long) abs(KopplungsteilNickRoll) * Parameter_CouplingYawCorrection) / 64L;
else TrimRoll -= ((long) abs(KopplungsteilNickRoll) * Parameter_CouplingYawCorrection) / 64L;
if(RohMesswertNick > 0) TrimNick += ((long) abs(KopplungsteilRollNick) * Parameter_CouplingYawCorrection) / 64L;
else TrimNick -= ((long) abs(KopplungsteilRollNick) * Parameter_CouplingYawCorrection) / 64L;
 
if(Parameter_GlobalConfig & CFG_DREHRATEN_BEGRENZER && !Looping_Nick && !Looping_Roll)
{
if(RohMesswertNick > 256) MesswertNick += 1 * (RohMesswertNick - 256);
else if(RohMesswertNick < -256) MesswertNick += 1 * (RohMesswertNick + 256);
if(RohMesswertRoll > 256) MesswertRoll += 1 * (RohMesswertRoll - 256);
else if(RohMesswertRoll < -256) MesswertRoll += 1 * (RohMesswertRoll + 256);
}
}
 
//############################################################################
// Senden der Motorwerte per I2C-Bus
void SendMotorData(void)
//############################################################################
{
unsigned char i;
if(!MotorenEin)
{
FC_StatusFlags &= ~(FC_STATUS_MOTOR_RUN | FC_STATUS_FLY);
for(i=0;i<MAX_MOTORS;i++)
{
if(!PC_MotortestActive) MotorTest[i] = 0;
Motor[i].SetPoint = MotorTest[i];
Motor[i].SetPointLowerBits = 0;
/*
Motor[i].SetPoint = MotorTest[i] / 4; // testing the high resolution
Motor[i].SetPointLowerBits = MotorTest[i] % 4;
*/
}
if(PC_MotortestActive) PC_MotortestActive--;
}
else FC_StatusFlags |= FC_STATUS_MOTOR_RUN;
 
if(I2C_TransferActive)
{
I2C_TransferActive = 0; // enable for the next time
}
else
{
motor_write = 0;
I2C_Start(TWI_STATE_MOTOR_TX); //Start I2C Interrupt Mode
}
}
 
 
 
//############################################################################
// Trägt ggf. das Poti als Parameter ein
void ParameterZuordnung(void)
//############################################################################
{
unsigned char tmp,i;
for(i=0;i<8;i++)
{
int tmp2;
tmp = EE_Parameter.Kanalbelegung[K_POTI1 + i];
tmp2 = PPM_in[tmp] + 127;
if(tmp2 > 255) tmp2 = 255; else if(tmp2 < 0) tmp2 = 0;
 
if(tmp == 25) Poti[i] = tmp2; // 25 = WaypointEvent channel -> no filter
else
if(tmp2 != Poti[i])
{
Poti[i] += (tmp2 - Poti[i]) / 4;
if(Poti[i] > tmp2) Poti[i]--;
else Poti[i]++;
}
}
CHK_POTI_MM(Parameter_Luftdruck_D,EE_Parameter.Luftdruck_D,0,100);
CHK_POTI_MM(Parameter_Hoehe_P,EE_Parameter.Hoehe_P,0,100);
CHK_POTI_MM(Parameter_Gyro_P,EE_Parameter.Gyro_P,10,255);
CHK_POTI_MM(Parameter_J16Timing,EE_Parameter.J16Timing,5,255);
CHK_POTI_MM(Parameter_J17Timing,EE_Parameter.J17Timing,5,255);
 
if(EE_Parameter.Servo3 == 247) { if(PORTC & (1<<PORTC2)) Parameter_Servo3 = 140; else Parameter_Servo3 = 70;} // Out1 (J16)
else if(EE_Parameter.Servo3 == 246) { if(PORTC & (1<<PORTC3)) Parameter_Servo3 = 140; else Parameter_Servo3 = 70;}
else CHK_POTI(Parameter_Servo3,EE_Parameter.Servo3);
 
if(EE_Parameter.Servo4 == 247) { if(PORTC & (1<<PORTC2)) Parameter_Servo4 = 140; else Parameter_Servo4 = 70;}
else if(EE_Parameter.Servo4 == 246) { if(PORTC & (1<<PORTC3)) Parameter_Servo4 = 140; else Parameter_Servo4 = 70;} // Out2 (J17)
else CHK_POTI(Parameter_Servo4,EE_Parameter.Servo4);
 
CHK_POTI(Parameter_Servo5,EE_Parameter.Servo5);
CHK_POTI(Parameter_HoehenSchalter,EE_Parameter.MaxHoehe);
CHK_POTI(Parameter_Hoehe_ACC_Wirkung,EE_Parameter.Hoehe_ACC_Wirkung);
CHK_POTI(Parameter_Hoehe_GPS_Z,EE_Parameter.Hoehe_GPS_Z);
CHK_POTI(Parameter_KompassWirkung,EE_Parameter.KompassWirkung);
CHK_POTI(Parameter_Gyro_I,EE_Parameter.Gyro_I);
CHK_POTI(Parameter_Gyro_D,EE_Parameter.Gyro_D);
CHK_POTI(Parameter_Gyro_Gier_P,EE_Parameter.Gyro_Gier_P);
CHK_POTI(Parameter_Gyro_Gier_I,EE_Parameter.Gyro_Gier_I);
CHK_POTI(Parameter_I_Faktor,EE_Parameter.I_Faktor);
CHK_POTI(Parameter_UserParam1,EE_Parameter.UserParam1);
CHK_POTI(Parameter_UserParam2,EE_Parameter.UserParam2);
CHK_POTI(Parameter_UserParam3,EE_Parameter.UserParam3);
CHK_POTI(Parameter_UserParam4,EE_Parameter.UserParam4);
CHK_POTI(Parameter_UserParam5,EE_Parameter.UserParam5);
CHK_POTI(Parameter_UserParam6,EE_Parameter.UserParam6);
CHK_POTI(Parameter_UserParam7,EE_Parameter.UserParam7);
CHK_POTI(Parameter_UserParam8,EE_Parameter.UserParam8);
CHK_POTI(Parameter_ServoNickControl,EE_Parameter.ServoNickControl);
CHK_POTI(Parameter_ServoRollControl,EE_Parameter.ServoRollControl);
CHK_POTI(Parameter_LoopGasLimit,EE_Parameter.LoopGasLimit);
CHK_POTI(Parameter_AchsKopplung1,EE_Parameter.AchsKopplung1);
CHK_POTI(Parameter_AchsKopplung2,EE_Parameter.AchsKopplung2);
CHK_POTI(Parameter_CouplingYawCorrection,EE_Parameter.CouplingYawCorrection);
CHK_POTI(Parameter_MaximumAltitude,EE_Parameter.MaxAltitude);
if((NC_To_FC_MaxAltitude && NC_To_FC_MaxAltitude < Parameter_MaximumAltitude) || Parameter_MaximumAltitude == 0) Parameter_MaximumAltitude = NC_To_FC_MaxAltitude;
Parameter_GlobalConfig = EE_Parameter.GlobalConfig;
Parameter_ExtraConfig = EE_Parameter.ExtraConfig;
// CHK_POTI(Parameter_AchsGegenKopplung1,EE_Parameter.AchsGegenKopplung1,0,255);
CHK_POTI(Parameter_DynamicStability,EE_Parameter.DynamicStability);
CHK_POTI(Parameter_ExternalControl,EE_Parameter.ExternalControl);
Ki = 10300 / (Parameter_I_Faktor + 1);
MAX_GAS = EE_Parameter.Gas_Max;
MIN_GAS = EE_Parameter.Gas_Min;
 
tmp = EE_Parameter.CareFreeModeControl;
if(tmp > 50)
{
CareFree = 1;
if(tmp >= 248 && Poti[255 - tmp] < 50) CareFree = 0;
if(carefree_old != CareFree)
{
if(carefree_old < 3)
{
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
if(CareFree) { beeptime = 1500; if(!SpeakHoTT) SpeakHoTT = SPEAK_CF_ON; }
else { beeptime = 200; if(!SpeakHoTT) SpeakHoTT = SPEAK_CF_OFF; }
#else
if(CareFree) beeptime = 1500;
else beeptime = 200;
#endif
NeueKompassRichtungMerken = 5;
carefree_old = CareFree;
} else carefree_old--;
}
if(FromNaviCtrl.CompassValue < 0 && CareFree) VersionInfo.HardwareError[0] |= FC_ERROR0_CAREFREE; //else VersionInfo.HardwareError[0] &= ~FC_ERROR0_CAREFREE;
}
else
{
CareFree = 0;
carefree_old = 10;
}
 
if(FromNaviCtrl.CompassValue < 0 && MotorenEin && CareFree && BeepMuster == 0xffff) // ungültiger Kompasswert
{
beeptime = 15000;
BeepMuster = 0xA400;
CareFree = 0;
}
if(CareFree) { FC_StatusFlags2 |= FC_STATUS2_CAREFREE; if(Parameter_AchsKopplung1 < 210) Parameter_AchsKopplung1 += 30;} else FC_StatusFlags2 &= ~FC_STATUS2_CAREFREE;
}
 
//############################################################################
//
void MotorRegler(void)
//############################################################################
{
int pd_ergebnis_nick,pd_ergebnis_roll,tmp_int, tmp_int2;
int GierMischanteil,GasMischanteil;
static long sollGier = 0,tmp_long,tmp_long2;
static long IntegralFehlerNick = 0;
static long IntegralFehlerRoll = 0;
static unsigned int RcLostTimer;
static unsigned char delay_neutral = 0;
static unsigned char delay_einschalten = 0,delay_ausschalten = 0;
static signed char move_safety_switch = 0;
static long ausgleichNick, ausgleichRoll;
int IntegralNickMalFaktor,IntegralRollMalFaktor;
unsigned char i;
Mittelwert();
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Gaswert ermitteln
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if(EE_Parameter.GlobalConfig3 & CFG3_VARIO_FAILSAFE)
{
if(HoverGas && HoverGas < 150 * STICK_GAIN)
{
HooverGasEmergencyPercent = (HoverGas/(STICK_GAIN) * EE_Parameter.NotGas) / 100; // i.e. 80% of Hovergas
}
else HooverGasEmergencyPercent = 45; // default if the Hoovergas was could not calculated yet
} else HooverGasEmergencyPercent = EE_Parameter.NotGas;
 
GasMischanteil = StickGas;
if(GasMischanteil < MIN_GAS + 10) GasMischanteil = MIN_GAS + 10;
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Empfang schlecht
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if(SenderOkay < 100 && !(FC_StatusFlags2 & FC_STATUS2_RC_FAILSAVE_ACTIVE))
{
if(RcLostTimer) RcLostTimer--;
else
{
MotorenEin = 0;
modell_fliegt = 0;
FC_StatusFlags &= ~(FC_STATUS_EMERGENCY_LANDING | FC_STATUS_FLY);
}
ROT_ON;
if(modell_fliegt > 1000 && Capacity.MinOfMaxPWM > 100) // wahrscheinlich in der Luft --> langsam absenken
{
GasMischanteil = HooverGasEmergencyPercent;
FC_StatusFlags |= FC_STATUS_EMERGENCY_LANDING;
PPM_diff[EE_Parameter.Kanalbelegung[K_NICK]] = 0;
PPM_diff[EE_Parameter.Kanalbelegung[K_ROLL]] = 0;
PPM_in[EE_Parameter.Kanalbelegung[K_NICK]] = 0;
PPM_in[EE_Parameter.Kanalbelegung[K_ROLL]] = 0;
PPM_in[EE_Parameter.Kanalbelegung[K_GIER]] = 0;
}
else
{
MotorenEin = 0;
}
}
else
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Emfang gut
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if(SenderOkay > 140)
{
FC_StatusFlags &= ~FC_STATUS_EMERGENCY_LANDING;
RcLostTimer = EE_Parameter.NotGasZeit * 50;
if(GasMischanteil > 40 && MotorenEin)
{
if(modell_fliegt < 0xffff) modell_fliegt++;
}
if((modell_fliegt < 256))
{
SummeNick = 0;
SummeRoll = 0;
sollGier = 0;
Mess_Integral_Gier = 0;
} else FC_StatusFlags |= FC_STATUS_FLY;
 
if((PPM_in[EE_Parameter.Kanalbelegung[K_GAS]] > 80) && MotorenEin == 0)
{
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// auf Nullwerte kalibrieren
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if(PPM_in[EE_Parameter.Kanalbelegung[K_GIER]] > 75) // Neutralwerte
{
if(++delay_neutral > 200) // nicht sofort
{
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
SpeakHoTT = SPEAK_CALIBRATE;
#endif
delay_neutral = 0;
modell_fliegt = 0;
if(PPM_in[EE_Parameter.Kanalbelegung[K_NICK]] > 70 || abs(PPM_in[EE_Parameter.Kanalbelegung[K_ROLL]]) > 70)
{
unsigned char setting=1;
if(PPM_in[EE_Parameter.Kanalbelegung[K_ROLL]] > 70 && PPM_in[EE_Parameter.Kanalbelegung[K_NICK]] < 70) setting = 1;
if(PPM_in[EE_Parameter.Kanalbelegung[K_ROLL]] > 70 && PPM_in[EE_Parameter.Kanalbelegung[K_NICK]] > 70) setting = 2;
if(PPM_in[EE_Parameter.Kanalbelegung[K_ROLL]] < 70 && PPM_in[EE_Parameter.Kanalbelegung[K_NICK]] > 70) setting = 3;
if(PPM_in[EE_Parameter.Kanalbelegung[K_ROLL]] <-70 && PPM_in[EE_Parameter.Kanalbelegung[K_NICK]] > 70) setting = 4;
if(PPM_in[EE_Parameter.Kanalbelegung[K_ROLL]] <-70 && PPM_in[EE_Parameter.Kanalbelegung[K_NICK]] < 70) setting = 5;
SetActiveParamSet(setting); // aktiven Datensatz merken
}
if(abs(PPM_in[EE_Parameter.Kanalbelegung[K_ROLL]]) < 30 && PPM_in[EE_Parameter.Kanalbelegung[K_NICK]] < -70)
{
WinkelOut.CalcState = 1;
CalibrationDone = 0;
beeptime = 1000;
}
else
{
ParamSet_ReadFromEEProm(GetActiveParamSet());
LipoDetection(0);
LIBFC_ReceiverInit(EE_Parameter.Receiver);
if((Parameter_GlobalConfig & CFG_HOEHENREGELUNG)) // Höhenregelung aktiviert?
{
if((MessLuftdruck > 950) || (MessLuftdruck < 750)) SucheLuftruckOffset();
}
// ServoActive = 0;
SetNeutral(0);
CalibrationDone = 1;
ServoActive = 1;
DDRD |=0x80; // enable J7 -> Servo signal
Piep(GetActiveParamSet(),120);
}
}
}
else
if(PPM_in[EE_Parameter.Kanalbelegung[K_GIER]] < -75) // ACC Neutralwerte speichern
{
if(++delay_neutral > 200) // nicht sofort
{
MotorenEin = 0;
delay_neutral = 0;
modell_fliegt = 0;
SetNeutral(1);
CalibrationDone = 1;
Piep(GetActiveParamSet(),120);
}
}
else delay_neutral = 0;
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Gas ist unten
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if(PPM_in[EE_Parameter.Kanalbelegung[K_GAS]] < 35-120)
{
if(PPM_diff[EE_Parameter.MotorSafetySwitch & 127] > 5) move_safety_switch = 100;
else
if(PPM_diff[EE_Parameter.MotorSafetySwitch & 127] < -5) move_safety_switch = -100;
// Motoren Starten
if(!MotorenEin)
{
if((((PPM_in[EE_Parameter.Kanalbelegung[K_GIER]] < -75) && ((!(EE_Parameter.GlobalConfig3 & CFG3_MOTOR_SWITCH_MODE) && PPM_in[EE_Parameter.MotorSafetySwitch] < -75) || EE_Parameter.MotorSafetySwitch == 0)))
|| (((EE_Parameter.GlobalConfig3 & CFG3_MOTOR_SWITCH_MODE) && PPM_in[EE_Parameter.MotorSafetySwitch] > -10 && move_safety_switch == 100)))
{
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Einschalten
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if(CalibrationDone) FC_StatusFlags |= FC_STATUS_START;
if(++delay_einschalten > 253)
{
delay_einschalten = 0;
if(!VersionInfo.HardwareError[0] && CalibrationDone && !NC_ErrorCode)
{
modell_fliegt = 1;
MotorenEin = 1;
sollGier = 0;
Mess_Integral_Gier = 0;
Mess_Integral_Gier2 = 0;
Mess_IntegralNick = EE_Parameter.GyroAccFaktor * (long)Mittelwert_AccNick;
Mess_IntegralRoll = EE_Parameter.GyroAccFaktor * (long)Mittelwert_AccRoll;
Mess_IntegralNick2 = IntegralNick;
Mess_IntegralRoll2 = IntegralRoll;
SummeNick = 0;
SummeRoll = 0;
// ControlHeading = (((int) EE_Parameter.OrientationAngle * 15 + KompassValue) % 360) / 2;
NeueKompassRichtungMerken = 100; // 2 sekunden
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
SpeakHoTT = SPEAK_STARTING;
#endif
}
else
{
beeptime = 1500; // indicate missing calibration
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
if(!CalibrationDone) SpeakHoTT = SPEAK_ERR_CALIBARTION;
#endif
}
}
}
else delay_einschalten = 0;
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Auschalten
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
else // only if motors are running
{
// if((PPM_in[EE_Parameter.Kanalbelegung[K_GIER]] > 75) && (PPM_in[EE_Parameter.MotorSafetySwitch] < -75 || EE_Parameter.MotorSafetySwitch == 0))
if((((PPM_in[EE_Parameter.Kanalbelegung[K_GIER]] > 75) && ((!(EE_Parameter.GlobalConfig3 & CFG3_MOTOR_SWITCH_MODE) && PPM_in[EE_Parameter.MotorSafetySwitch] < -75) || EE_Parameter.MotorSafetySwitch == 0)))
|| (((EE_Parameter.GlobalConfig3 & CFG3_MOTOR_SWITCH_MODE) && PPM_in[EE_Parameter.MotorSafetySwitch] < -50 && move_safety_switch == -100)))
{
if(++delay_ausschalten > 250) // nicht sofort
{
MotorenEin = 0;
delay_ausschalten = 0;
modell_fliegt = 0;
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
SpeakHoTT = SPEAK_MK_OFF;
#endif
}
}
else delay_ausschalten = 0;
}
}
else // gas not at minimum
move_safety_switch = 0;
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// neue Werte von der Funke
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 
if(!NewPpmData-- || (FC_StatusFlags & FC_STATUS_EMERGENCY_LANDING))
{
static int stick_nick,stick_roll;
unsigned char stick_p;
ParameterZuordnung();
stick_p = EE_Parameter.Stick_P;
stick_nick = (stick_nick * 3 + PPM_in[EE_Parameter.Kanalbelegung[K_NICK]] * stick_p) / 4;
stick_nick += PPM_diff[EE_Parameter.Kanalbelegung[K_NICK]] * EE_Parameter.Stick_D;
stick_roll = (stick_roll * 3 + PPM_in[EE_Parameter.Kanalbelegung[K_ROLL]] * stick_p) / 4;
stick_roll += PPM_diff[EE_Parameter.Kanalbelegung[K_ROLL]] * EE_Parameter.Stick_D;
 
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// CareFree und freie Wahl der vorderen Richtung
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if(CareFree)
{
signed int nick, roll;
nick = stick_nick / 4;
roll = stick_roll / 4;
StickNick = ((FromNC_Rotate_C * nick) + (FromNC_Rotate_S * roll)) / (32 / 4);
StickRoll = ((FromNC_Rotate_C * roll) - (FromNC_Rotate_S * nick)) / (32 / 4);
}
else
{
FromNC_Rotate_C = sintab[EE_Parameter.OrientationAngle + 6];
FromNC_Rotate_S = sintab[EE_Parameter.OrientationAngle];
StickNick = ((FromNC_Rotate_C * stick_nick) + (FromNC_Rotate_S * stick_roll)) / 8;
StickRoll = ((FromNC_Rotate_C * stick_roll) - (FromNC_Rotate_S * stick_nick)) / 8;
}
 
StickGier = -PPM_in[EE_Parameter.Kanalbelegung[K_GIER]];
if(StickGier > 4) StickGier -= 4; else
if(StickGier < -4) StickGier += 4; else StickGier = 0;
 
if(GPS_Aid_StickMultiplikator) // in that case the GPS controls stronger
{
StickNick = (GPS_Aid_StickMultiplikator * (StickNick / 8)) / 16;
StickRoll = (GPS_Aid_StickMultiplikator * (StickRoll / 8)) / 16;
}
 
StickNick -= GPS_Nick;
StickRoll -= GPS_Roll;
StickGas = PPM_in[EE_Parameter.Kanalbelegung[K_GAS]] + 127;
 
GyroFaktor = (Parameter_Gyro_P + 10.0);
IntegralFaktor = Parameter_Gyro_I;
GyroFaktorGier = (Parameter_Gyro_Gier_P + 10.0);
IntegralFaktorGier = Parameter_Gyro_Gier_I;
 
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+ Analoge Steuerung per Seriell
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if(ExternControl.Config & 0x01 && Parameter_ExternalControl > 128)
{
StickNick += (int) ExternControl.Nick * (int) EE_Parameter.Stick_P;
StickRoll += (int) ExternControl.Roll * (int) EE_Parameter.Stick_P;
StickGier += ExternControl.Gier;
ExternHoehenValue = (int) ExternControl.Hight * (int)EE_Parameter.Hoehe_Verstaerkung;
if(ExternControl.Gas < StickGas) StickGas = ExternControl.Gas;
}
if(StickGas < 0) StickGas = 0;
 
if(Parameter_GlobalConfig & CFG_HEADING_HOLD) IntegralFaktor = 0;
 
if(abs(StickNick/STICK_GAIN) > MaxStickNick)
{
MaxStickNick = abs(StickNick)/STICK_GAIN;
if(MaxStickNick > 100) MaxStickNick = 100;
}
else MaxStickNick--;
if(abs(StickRoll/STICK_GAIN) > MaxStickRoll)
{
MaxStickRoll = abs(StickRoll)/STICK_GAIN;
if(MaxStickRoll > 100) MaxStickRoll = 100;
}
else MaxStickRoll--;
if(FC_StatusFlags & FC_STATUS_EMERGENCY_LANDING) {MaxStickNick = 0; MaxStickRoll = 0;}
 
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Looping?
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if((PPM_in[EE_Parameter.Kanalbelegung[K_ROLL]] > EE_Parameter.LoopThreshold) && EE_Parameter.BitConfig & CFG_LOOP_LINKS) Looping_Links = 1;
else
{
{
if((PPM_in[EE_Parameter.Kanalbelegung[K_ROLL]] < (EE_Parameter.LoopThreshold - EE_Parameter.LoopHysterese))) Looping_Links = 0;
}
}
if((PPM_in[EE_Parameter.Kanalbelegung[K_ROLL]] < -EE_Parameter.LoopThreshold) && EE_Parameter.BitConfig & CFG_LOOP_RECHTS) Looping_Rechts = 1;
else
{
if(Looping_Rechts) // Hysterese
{
if(PPM_in[EE_Parameter.Kanalbelegung[K_ROLL]] > -(EE_Parameter.LoopThreshold - EE_Parameter.LoopHysterese)) Looping_Rechts = 0;
}
}
 
if((PPM_in[EE_Parameter.Kanalbelegung[K_NICK]] > EE_Parameter.LoopThreshold) && EE_Parameter.BitConfig & CFG_LOOP_OBEN) Looping_Oben = 1;
else
{
if(Looping_Oben) // Hysterese
{
if((PPM_in[EE_Parameter.Kanalbelegung[K_NICK]] < (EE_Parameter.LoopThreshold - EE_Parameter.LoopHysterese))) Looping_Oben = 0;
}
}
if((PPM_in[EE_Parameter.Kanalbelegung[K_NICK]] < -EE_Parameter.LoopThreshold) && EE_Parameter.BitConfig & CFG_LOOP_UNTEN) Looping_Unten = 1;
else
{
if(Looping_Unten) // Hysterese
{
if(PPM_in[EE_Parameter.Kanalbelegung[K_NICK]] > -(EE_Parameter.LoopThreshold - EE_Parameter.LoopHysterese)) Looping_Unten = 0;
}
}
 
if(Looping_Links || Looping_Rechts) Looping_Roll = 1; else Looping_Roll = 0;
if(Looping_Oben || Looping_Unten) { Looping_Nick = 1; Looping_Roll = 0; Looping_Links = 0; Looping_Rechts = 0;} else Looping_Nick = 0;
} // Ende neue Funken-Werte
 
if(Looping_Roll || Looping_Nick)
{
if(GasMischanteil > EE_Parameter.LoopGasLimit) GasMischanteil = EE_Parameter.LoopGasLimit;
TrichterFlug = 1;
}
 
 
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Bei Empfangsausfall im Flug
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if(FC_StatusFlags2 & FC_STATUS2_RC_FAILSAVE_ACTIVE)
{
StickNick = -GPS_Nick;
StickRoll = -GPS_Roll;
StickGas = StickGasHover;
Parameter_GlobalConfig &= ~(CFG_HEADING_HOLD | CFG_DREHRATEN_BEGRENZER);
Parameter_GlobalConfig |= CFG_HOEHENREGELUNG | CFG_ACHSENKOPPLUNG_AKTIV | CFG_KOMPASS_AKTIV | CFG_GPS_AKTIV | CFG_HOEHEN_SCHALTER | CFG_GPS_AKTIV;
Parameter_ExtraConfig &= ~(CFG2_HEIGHT_LIMIT | CFG_LEARNABLE_CAREFREE | CFG2_VARIO_BEEP);
Parameter_HoehenSchalter = 200; // switch on
}
else
if(FC_StatusFlags & FC_STATUS_EMERGENCY_LANDING)
{
StickGier = 0;
StickNick = 0;
StickRoll = 0;
GyroFaktor = 90;
IntegralFaktor = 120;
GyroFaktorGier = 90;
IntegralFaktorGier = 120;
Looping_Roll = 0;
Looping_Nick = 0;
}
 
 
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Integrale auf ACC-Signal abgleichen
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#define ABGLEICH_ANZAHL 256L
 
MittelIntegralNick += IntegralNick; // Für die Mittelwertbildung aufsummieren
MittelIntegralRoll += IntegralRoll;
MittelIntegralNick2 += IntegralNick2;
MittelIntegralRoll2 += IntegralRoll2;
 
if(Looping_Nick || Looping_Roll)
{
IntegralAccNick = 0;
IntegralAccRoll = 0;
MittelIntegralNick = 0;
MittelIntegralRoll = 0;
MittelIntegralNick2 = 0;
MittelIntegralRoll2 = 0;
Mess_IntegralNick2 = Mess_IntegralNick;
Mess_IntegralRoll2 = Mess_IntegralRoll;
ZaehlMessungen = 0;
LageKorrekturNick = 0;
LageKorrekturRoll = 0;
}
 
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if(!Looping_Nick && !Looping_Roll && (Aktuell_az > 512 || MotorenEin))
{
long tmp_long, tmp_long2;
if(FromNaviCtrl_Value.Kalman_K > 0 /*&& !TrichterFlug*/)
{
tmp_long = (long)(IntegralNick / EE_Parameter.GyroAccFaktor - (long)(Mittelwert_AccNick - FromNaviCtrl.AccErrorN));
tmp_long2 = (long)(IntegralRoll / EE_Parameter.GyroAccFaktor - (long)(Mittelwert_AccRoll - FromNaviCtrl.AccErrorR));
tmp_long = (tmp_long * FromNaviCtrl_Value.Kalman_K) / (32 * 16);
tmp_long2 = (tmp_long2 * FromNaviCtrl_Value.Kalman_K) / (32 * 16);
if((MaxStickNick > 64) || (MaxStickRoll > 64))
{
tmp_long /= 2;
tmp_long2 /= 2;
}
if(abs(PPM_in[EE_Parameter.Kanalbelegung[K_GIER]]) > 25)
{
tmp_long /= 3;
tmp_long2 /= 3;
}
long kmf = FromNaviCtrl_Value.Kalman_MaxFusion;
if(tmp_long > (long) kmf) tmp_long = (long) kmf;
if(tmp_long < (long)-kmf) tmp_long = (long)-kmf;
if(tmp_long2 > (long) kmf) tmp_long2 = (long) kmf;
if(tmp_long2 < (long)-kmf) tmp_long2 = (long)-kmf;
}
else
{
tmp_long = (long)(IntegralNick / EE_Parameter.GyroAccFaktor - (long)Mittelwert_AccNick);
tmp_long2 = (long)(IntegralRoll / EE_Parameter.GyroAccFaktor - (long)Mittelwert_AccRoll);
tmp_long /= 16;
tmp_long2 /= 16;
if((MaxStickNick > 64) || (MaxStickRoll > 64))
{
tmp_long /= 3;
tmp_long2 /= 3;
}
if(abs(PPM_in[EE_Parameter.Kanalbelegung[K_GIER]]) > 25)
{
tmp_long /= 3;
tmp_long2 /= 3;
}
KompassFusion = 25;
#define AUSGLEICH 32
if(tmp_long > AUSGLEICH) tmp_long = AUSGLEICH;
if(tmp_long < -AUSGLEICH) tmp_long =-AUSGLEICH;
if(tmp_long2 > AUSGLEICH) tmp_long2 = AUSGLEICH;
if(tmp_long2 <-AUSGLEICH) tmp_long2 =-AUSGLEICH;
}
 
Mess_IntegralNick -= tmp_long;
Mess_IntegralRoll -= tmp_long2;
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if(ZaehlMessungen >= ABGLEICH_ANZAHL)
{
static int cnt = 0;
static char last_n_p,last_n_n,last_r_p,last_r_n;
static long MittelIntegralNick_Alt,MittelIntegralRoll_Alt;
if(!Looping_Nick && !Looping_Roll && !TrichterFlug && EE_Parameter.Driftkomp)
{
MittelIntegralNick /= ABGLEICH_ANZAHL;
MittelIntegralRoll /= ABGLEICH_ANZAHL;
IntegralAccNick = (EE_Parameter.GyroAccFaktor * IntegralAccNick) / ABGLEICH_ANZAHL;
IntegralAccRoll = (EE_Parameter.GyroAccFaktor * IntegralAccRoll) / ABGLEICH_ANZAHL;
IntegralAccZ = IntegralAccZ / ABGLEICH_ANZAHL;
#define MAX_I 0
// Nick ++++++++++++++++++++++++++++++++++++++++++++++++
IntegralFehlerNick = (long)(MittelIntegralNick - (long)IntegralAccNick);
ausgleichNick = IntegralFehlerNick / EE_Parameter.GyroAccAbgleich;
// Roll ++++++++++++++++++++++++++++++++++++++++++++++++
IntegralFehlerRoll = (long)(MittelIntegralRoll - (long)IntegralAccRoll);
ausgleichRoll = IntegralFehlerRoll / EE_Parameter.GyroAccAbgleich;
 
LageKorrekturNick = ausgleichNick / ABGLEICH_ANZAHL;
LageKorrekturRoll = ausgleichRoll / ABGLEICH_ANZAHL;
 
if(((MaxStickNick > 64) || (MaxStickRoll > 64) || (abs(PPM_in[EE_Parameter.Kanalbelegung[K_GIER]]) > 25)) && (FromNaviCtrl_Value.Kalman_K == -1))
{
LageKorrekturNick /= 2;
LageKorrekturRoll /= 2;
}
 
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Gyro-Drift ermitteln
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MittelIntegralNick2 /= ABGLEICH_ANZAHL;
MittelIntegralRoll2 /= ABGLEICH_ANZAHL;
tmp_long = IntegralNick2 - IntegralNick;
tmp_long2 = IntegralRoll2 - IntegralRoll;
 
IntegralFehlerNick = tmp_long;
IntegralFehlerRoll = tmp_long2;
Mess_IntegralNick2 -= IntegralFehlerNick;
Mess_IntegralRoll2 -= IntegralFehlerRoll;
 
if(EE_Parameter.Driftkomp)
{
if(GierGyroFehler > ABGLEICH_ANZAHL/2) { AdNeutralGier++; }
if(GierGyroFehler <-ABGLEICH_ANZAHL/2) { AdNeutralGier--; }
}
GierGyroFehler = 0;
 
#define FEHLER_LIMIT (ABGLEICH_ANZAHL / 2)
#define FEHLER_LIMIT1 (ABGLEICH_ANZAHL * 2) //4
#define FEHLER_LIMIT2 (ABGLEICH_ANZAHL * 16) //16
#define BEWEGUNGS_LIMIT 20000
// Nick +++++++++++++++++++++++++++++++++++++++++++++++++
cnt = 1;// + labs(IntegralFehlerNick) / 4096;
if(labs(IntegralFehlerNick) > FEHLER_LIMIT1) cnt = 4;
if(labs(MittelIntegralNick_Alt - MittelIntegralNick) < BEWEGUNGS_LIMIT || (FromNaviCtrl_Value.Kalman_MaxDrift > 3*8))
{
if(IntegralFehlerNick > FEHLER_LIMIT2)
{
if(last_n_p)
{
cnt += labs(IntegralFehlerNick) / (FEHLER_LIMIT2 / 8);
ausgleichNick = IntegralFehlerNick / 8;
if(ausgleichNick > 5000) ausgleichNick = 5000;
LageKorrekturNick += ausgleichNick / ABGLEICH_ANZAHL;
}
else last_n_p = 1;
} else last_n_p = 0;
if(IntegralFehlerNick < -FEHLER_LIMIT2)
{
if(last_n_n)
{
cnt += labs(IntegralFehlerNick) / (FEHLER_LIMIT2 / 8);
ausgleichNick = IntegralFehlerNick / 8;
if(ausgleichNick < -5000) ausgleichNick = -5000;
LageKorrekturNick += ausgleichNick / ABGLEICH_ANZAHL;
}
else last_n_n = 1;
} else last_n_n = 0;
}
else
{
cnt = 0;
KompassSignalSchlecht = 100;
}
if(cnt > EE_Parameter.Driftkomp) cnt = EE_Parameter.Driftkomp;
if(FromNaviCtrl_Value.Kalman_MaxDrift) if(cnt > FromNaviCtrl_Value.Kalman_MaxDrift) cnt = FromNaviCtrl_Value.Kalman_MaxDrift;
if(IntegralFehlerNick > FEHLER_LIMIT) AdNeutralNick += cnt;
if(IntegralFehlerNick < -FEHLER_LIMIT) AdNeutralNick -= cnt;
 
// Roll +++++++++++++++++++++++++++++++++++++++++++++++++
cnt = 1;// + labs(IntegralFehlerRoll) / 4096;
if(labs(IntegralFehlerRoll) > FEHLER_LIMIT1) cnt = 4;
if(labs(MittelIntegralRoll_Alt - MittelIntegralRoll) < BEWEGUNGS_LIMIT || (FromNaviCtrl_Value.Kalman_MaxDrift > 3*8))
{
if(IntegralFehlerRoll > FEHLER_LIMIT2)
{
if(last_r_p)
{
cnt += labs(IntegralFehlerRoll) / (FEHLER_LIMIT2 / 8);
ausgleichRoll = IntegralFehlerRoll / 8;
if(ausgleichRoll > 5000) ausgleichRoll = 5000;
LageKorrekturRoll += ausgleichRoll / ABGLEICH_ANZAHL;
}
else last_r_p = 1;
} else last_r_p = 0;
if(IntegralFehlerRoll < -FEHLER_LIMIT2)
{
if(last_r_n)
{
cnt += labs(IntegralFehlerRoll) / (FEHLER_LIMIT2 / 8);
ausgleichRoll = IntegralFehlerRoll / 8;
if(ausgleichRoll < -5000) ausgleichRoll = -5000;
LageKorrekturRoll += ausgleichRoll / ABGLEICH_ANZAHL;
}
else last_r_n = 1;
} else last_r_n = 0;
} else
{
cnt = 0;
KompassSignalSchlecht = 100;
}
if(cnt > EE_Parameter.Driftkomp) cnt = EE_Parameter.Driftkomp;
if(FromNaviCtrl_Value.Kalman_MaxDrift) if(cnt > FromNaviCtrl_Value.Kalman_MaxDrift) cnt = FromNaviCtrl_Value.Kalman_MaxDrift;
if(IntegralFehlerRoll > FEHLER_LIMIT) AdNeutralRoll += cnt;
if(IntegralFehlerRoll < -FEHLER_LIMIT) AdNeutralRoll -= cnt;
}
else
{
LageKorrekturRoll = 0;
LageKorrekturNick = 0;
TrichterFlug = 0;
}
 
if(!IntegralFaktor) { LageKorrekturRoll = 0; LageKorrekturNick = 0;} // z.B. bei HH
// +++++++++++++++++++++++++++++++++++++++++++++++++++++
MittelIntegralNick_Alt = MittelIntegralNick;
MittelIntegralRoll_Alt = MittelIntegralRoll;
// +++++++++++++++++++++++++++++++++++++++++++++++++++++
IntegralAccNick = 0;
IntegralAccRoll = 0;
IntegralAccZ = 0;
MittelIntegralNick = 0;
MittelIntegralRoll = 0;
MittelIntegralNick2 = 0;
MittelIntegralRoll2 = 0;
ZaehlMessungen = 0;
} // ZaehlMessungen >= ABGLEICH_ANZAHL
 
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Gieren
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if(abs(StickGier) > 3) // war 15
{
// KompassSignalSchlecht = 1000;
if(!(Parameter_GlobalConfig & CFG_KOMPASS_FIX))
{
NeueKompassRichtungMerken = 50; // eine Sekunde zum Einloggen
};
}
tmp_int = (long) EE_Parameter.StickGier_P * ((long)StickGier * abs(StickGier)) / 512L; // expo y = ax + bx²
tmp_int += (EE_Parameter.StickGier_P * StickGier) / 4;
tmp_int += CompassGierSetpoint;
sollGier = tmp_int;
Mess_Integral_Gier -= tmp_int;
if(Mess_Integral_Gier > 50000) Mess_Integral_Gier = 50000; // begrenzen
if(Mess_Integral_Gier <-50000) Mess_Integral_Gier =-50000;
 
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Kompass
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if(KompassValue >= 0 && (Parameter_GlobalConfig & CFG_KOMPASS_AKTIV))
{
if(CalculateCompassTimer-- == 1)
{
int w,v,r,fehler,korrektur; // wird von der SPI-Routine auf 1 gesetzt
CalculateCompassTimer = 13; // falls keine Navi-Daten
// max. Korrekturwert schätzen
w = abs(IntegralNick /512); // mit zunehmender Neigung den Einfluss drosseln
v = abs(IntegralRoll /512);
if(v > w) w = v; // grösste Neigung ermitteln
// korrektur = w / 4 + 1;
korrektur = w / 8 + 2;
ErsatzKompassInGrad = ErsatzKompass/GIER_GRAD_FAKTOR;
// Kompassfehlerwert bestimmen
fehler = ((540 + KompassValue - ErsatzKompassInGrad) % 360) - 180;
// GIER_GRAD_FAKTOR ist ca. 1200
// Kompasswert einloggen
if(KompassSignalSchlecht) KompassSignalSchlecht--;
else
if(w < 25)
{
GierGyroFehler += fehler;
if(NeueKompassRichtungMerken)
{
if(--NeueKompassRichtungMerken == 0)
{
KompassSollWert = ErsatzKompassInGrad;
}
}
}
// Kompass fusionieren
if(!KompassSignalSchlecht) ErsatzKompass += (fehler * KompassFusion) / korrektur;
// MK Gieren
if(!NeueKompassRichtungMerken)
{
r = ((540 + (KompassSollWert - ErsatzKompassInGrad)) % 360) - 180;
v = r * (Parameter_KompassWirkung/2); // nach Kompass ausrichten
CompassGierSetpoint = v / 16;
}
else CompassGierSetpoint = 0;
} // CalculateCompassTimer
}
else CompassGierSetpoint = 0;
 
//DebugOut.Analog[16] = KompassFusion;
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Drehgeschwindigkeit und -winkel zu einem Istwert zusammenfassen
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if(TrichterFlug) { SummeRoll = 0; SummeNick = 0;};
 
if(!Looping_Nick) IntegralNickMalFaktor = (IntegralNick * IntegralFaktor) / (44000 / STICK_GAIN); else IntegralNickMalFaktor = 0;
if(!Looping_Roll) IntegralRollMalFaktor = (IntegralRoll * IntegralFaktor) / (44000 / STICK_GAIN); else IntegralRollMalFaktor = 0;
 
#define TRIM_MAX 200
if(TrimNick > TRIM_MAX) TrimNick = TRIM_MAX; else if(TrimNick <-TRIM_MAX) TrimNick =-TRIM_MAX;
if(TrimRoll > TRIM_MAX) TrimRoll = TRIM_MAX; else if(TrimRoll <-TRIM_MAX) TrimRoll =-TRIM_MAX;
 
MesswertNick = IntegralNickMalFaktor + (long)((long)MesswertNick * GyroFaktor + (long)TrimNick * 128L) / (256L / STICK_GAIN);
MesswertRoll = IntegralRollMalFaktor + (long)((long)MesswertRoll * GyroFaktor + (long)TrimRoll * 128L) / (256L / STICK_GAIN);
MesswertGier = (long)(MesswertGier * 2 * (long)GyroFaktorGier) / (256L / STICK_GAIN) + (long)(Integral_Gier * IntegralFaktorGier) / (2 * (44000 / STICK_GAIN));
 
// Maximalwerte abfangen
#define MAX_SENSOR (4096)
if(MesswertNick > MAX_SENSOR) MesswertNick = MAX_SENSOR;
if(MesswertNick < -MAX_SENSOR) MesswertNick = -MAX_SENSOR;
if(MesswertRoll > MAX_SENSOR) MesswertRoll = MAX_SENSOR;
if(MesswertRoll < -MAX_SENSOR) MesswertRoll = -MAX_SENSOR;
if(MesswertGier > MAX_SENSOR) MesswertGier = MAX_SENSOR;
if(MesswertGier < -MAX_SENSOR) MesswertGier = -MAX_SENSOR;
 
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Höhenregelung
// Die Höhenregelung schwächt lediglich das Gas ab, erhöht es allerdings nicht
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if(UBat > BattLowVoltageWarning) GasMischanteil = ((unsigned int)GasMischanteil * BattLowVoltageWarning) / UBat; // Gas auf das aktuelle Spannungvieveau beziehen
GasMischanteil *= STICK_GAIN;
// if height control is activated
if((Parameter_GlobalConfig & CFG_HOEHENREGELUNG) && !(Looping_Roll || Looping_Nick)) // Höhenregelung
{
#define HOVER_GAS_AVERAGE 16384L // 16384 * 2ms = 32s averaging
#define HC_GAS_AVERAGE 4 // 4 * 2ms= 8ms averaging
 
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
#define OPA_OFFSET_STEP 15
#else
#define OPA_OFFSET_STEP 10
#endif
int HCGas, HeightDeviation = 0,GasReduction = 0;
static int HeightTrimming = 0; // rate for change of height setpoint
static int FilterHCGas = 0;
static unsigned long HoverGasFilter = 0;
static unsigned char delay = 100, BaroAtUpperLimit = 0, BaroAtLowerLimit = 0;
int CosAttitude; // for projection of hoover gas
 
// get the current hooverpoint
DebugOut.Analog[21] = HoverGas;
 
// Expand the measurement
// measurement of air pressure close to upper limit and no overflow in correction of the new OCR0A value occurs
if(!BaroExpandActive)
{
if(MessLuftdruck > 920)
{ // increase offset
if(OCR0A < (255 - OPA_OFFSET_STEP))
{
ExpandBaro -= 1;
OCR0A = DruckOffsetSetting - OPA_OFFSET_STEP * ExpandBaro; // increase offset to shift ADC down
beeptime = 300;
BaroExpandActive = 350;
}
else
{
BaroAtLowerLimit = 1;
}
}
// measurement of air pressure close to lower limit and
else
if(MessLuftdruck < 100)
{ // decrease offset
if(OCR0A > OPA_OFFSET_STEP)
{
ExpandBaro += 1;
OCR0A = DruckOffsetSetting - OPA_OFFSET_STEP * ExpandBaro; // decrease offset to shift ADC up
beeptime = 300;
BaroExpandActive = 350;
}
else
{
BaroAtUpperLimit = 1;
}
}
else
{
BaroAtUpperLimit = 0;
BaroAtLowerLimit = 0;
}
}
else // delay, because of expanding the Baro-Range
{
// now clear the D-values
SummenHoehe = HoehenWert * SM_FILTER;
VarioMeter = 0;
BaroExpandActive--;
}
 
// if height control is activated by an rc channel
if(Parameter_GlobalConfig & CFG_HOEHEN_SCHALTER) // Regler wird über Schalter gesteuert
{ // check if parameter is less than activation threshold
if(Parameter_HoehenSchalter < 50) // for 3 or 2-state switch height control is disabled in lowest position
{ //height control not active
if(!delay--)
{
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
if(HoehenReglerAktiv && !SpeakHoTT) SpeakHoTT = SPEAK_ALTITUDE_OFF;
#endif
HoehenReglerAktiv = 0; // disable height control
SollHoehe = HoehenWert; // update SetPoint with current reading
delay = 1;
}
}
else
if(Parameter_HoehenSchalter > 70)
{ //height control is activated
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
if(!HoehenReglerAktiv && !SpeakHoTT) SpeakHoTT = SPEAK_ALTITUDE_ON;
#endif
HoehenReglerAktiv = 1; // enable height control
delay = 200;
}
}
else // no switchable height control
{
SollHoehe = ((int16_t) ExternHoehenValue + (int16_t) Parameter_HoehenSchalter) * (int)EE_Parameter.Hoehe_Verstaerkung;
HoehenReglerAktiv = 1;
}
 
// calculate cos of nick and roll angle used for projection of the vertical hoover gas
tmp_int = (int)(IntegralNick/GIER_GRAD_FAKTOR); // nick angle in deg
tmp_int2 = (int)(IntegralRoll/GIER_GRAD_FAKTOR); // roll angle in deg
CosAttitude = (int16_t)ihypot(tmp_int, tmp_int2); // phytagoras gives effective attitude angle in deg
LIMIT_MAX(CosAttitude, 60); // limit effective attitude angle
CosAttitude = c_cos_8192(CosAttitude); // cos of actual attitude
VarioCharacter = ' ';
AltitudeSetpointTrimming = 0;
if(HoehenReglerAktiv && !(FC_StatusFlags & FC_STATUS_EMERGENCY_LANDING))
{
#define HEIGHT_CONTROL_STICKTHRESHOLD 15
// Holger original version
// start of height control algorithm
// the height control is only an attenuation of the actual gas stick.
// I.e. it will work only if the gas stick is higher than the hover gas
// and the hover height will be allways larger than height setpoint.
FC_StatusFlags2 |= FC_STATUS2_ALTITUDE_CONTROL;
if((Parameter_ExtraConfig & CFG2_HEIGHT_LIMIT) || !(Parameter_GlobalConfig & CFG_HOEHEN_SCHALTER)) // Regler wird über Schalter gesteuert)
{ // old version
HCGas = GasMischanteil; // take current stick gas as neutral point for the height control
HeightTrimming = 0;
AltitudeSetpointTrimming = 0;
// set both flags to indicate no vario mode
FC_StatusFlags |= (FC_STATUS_VARIO_TRIM_UP|FC_STATUS_VARIO_TRIM_DOWN);
}
else
{
// alternative height control
// PD-Control with respect to hoover point
// the thrust loss out of horizontal attitude is compensated
// the setpoint will be fine adjusted with the gas stick position
if(FC_StatusFlags & FC_STATUS_FLY) // trim setpoint only when flying
{ // gas stick is above hoover point
if(StickGas > (StickGasHover + HEIGHT_CONTROL_STICKTHRESHOLD) && !BaroAtUpperLimit)
{
if(FC_StatusFlags & FC_STATUS_VARIO_TRIM_DOWN)
{
FC_StatusFlags &= ~FC_STATUS_VARIO_TRIM_DOWN;
SollHoehe = HoehenWert; // update setpoint to current heigth
}
FC_StatusFlags |= FC_STATUS_VARIO_TRIM_UP;
// Limit the maximum Altitude
if(Parameter_MaximumAltitude && (SollHoehe/100 > Parameter_MaximumAltitude)) AltitudeSetpointTrimming = 0;
else
{
// SollHoehe = (long) Parameter_MaximumAltitude * 100L;
// HeightTrimming += abs(StickGas - (StickGasHover - HEIGHT_CONTROL_STICKTHRESHOLD));
AltitudeSetpointTrimming = abs(StickGas - (StickGasHover + HEIGHT_CONTROL_STICKTHRESHOLD));
VarioCharacter = '+';
}
WaypointTrimming = 0;
} // gas stick is below hoover point
else if(StickGas < (StickGasHover - HEIGHT_CONTROL_STICKTHRESHOLD) && !BaroAtLowerLimit )
{
if(FC_StatusFlags & FC_STATUS_VARIO_TRIM_UP)
{
FC_StatusFlags &= ~FC_STATUS_VARIO_TRIM_UP;
SollHoehe = HoehenWert; // update setpoint to current heigth
}
FC_StatusFlags |= FC_STATUS_VARIO_TRIM_DOWN;
AltitudeSetpointTrimming = -abs(StickGas - (StickGasHover - HEIGHT_CONTROL_STICKTHRESHOLD));
// HeightTrimming -= abs(StickGas - (StickGasHover - HEIGHT_CONTROL_STICKTHRESHOLD));
VarioCharacter = '-';
WaypointTrimming = 0;
}
else // Gas Stick in Hover Range
{
VarioCharacter = '=';
if(FromNC_AltitudeSpeed && FromNC_AltitudeSetpoint > SollHoehe) // von NC gesteuert -> Steigen
{
FC_StatusFlags |= FC_STATUS_VARIO_TRIM_UP;
AltitudeSetpointTrimming = FromNC_AltitudeSpeed;
//HeightTrimming += FromNC_AltitudeSpeed;
WaypointTrimming = 10;
VarioCharacter = '^';
if(FC_StatusFlags & FC_STATUS_VARIO_TRIM_DOWN) // changed from sinking to rising
{
FC_StatusFlags &= ~FC_STATUS_VARIO_TRIM_DOWN;
SollHoehe = HoehenWert; // update setpoint to current heigth
}
}
else
if(FromNC_AltitudeSpeed && FromNC_AltitudeSetpoint < SollHoehe) // von NC gesteuert -> sinken
{
FC_StatusFlags |= FC_STATUS_VARIO_TRIM_DOWN;
AltitudeSetpointTrimming = -FromNC_AltitudeSpeed;
//HeightTrimming -= FromNC_AltitudeSpeed;
WaypointTrimming = -10;
VarioCharacter = 'v';
if(FC_StatusFlags & FC_STATUS_VARIO_TRIM_UP) // changed from rising to sinking
{
FC_StatusFlags &= ~FC_STATUS_VARIO_TRIM_UP;
SollHoehe = HoehenWert; // update setpoint to current heigth
}
}
else
if(FC_StatusFlags & (FC_STATUS_VARIO_TRIM_UP|FC_STATUS_VARIO_TRIM_DOWN))
{
if(!WaypointTrimming) LIMIT_MIN_MAX(SollHoehe, (HoehenWert-128), (HoehenWert+128)) // max. 1m Unterschied
else WaypointTrimming = 0;
FC_StatusFlags &= ~(FC_STATUS_VARIO_TRIM_UP|FC_STATUS_VARIO_TRIM_DOWN);
HeightTrimming = 0;
if(Parameter_ExtraConfig & CFG2_VARIO_BEEP) beeptime = 500;
if(!StartTrigger && HoehenWert > 50)
{
StartTrigger = 1;
}
}
}
// Trim height set point
HeightTrimming += AltitudeSetpointTrimming;
if(abs(HeightTrimming) > 500) // bei Waypoint-Flug ist das ca. die 500Hz
{
if(WaypointTrimming)
{
if(abs(FromNC_AltitudeSetpoint - SollHoehe) < 10) SollHoehe = FromNC_AltitudeSetpoint;
else SollHoehe += WaypointTrimming;
}
else
{
if(HeightTrimming > 0) SollHoehe += EE_Parameter.Hoehe_Verstaerkung / 3;
else SollHoehe -= EE_Parameter.Hoehe_Verstaerkung / 3;
}
HeightTrimming = 0;
LIMIT_MIN_MAX(SollHoehe, (HoehenWert-1024), (HoehenWert+1024)); // max. 10m Unterschied
if(Parameter_ExtraConfig & CFG2_VARIO_BEEP) beeptime = 100;
//update hoover gas stick value when setpoint is shifted
if(!EE_Parameter.Hoehe_StickNeutralPoint && FromNC_AltitudeSpeed == 0)
{
StickGasHover = HoverGas/STICK_GAIN; //rescale back to stick value
StickGasHover = (StickGasHover * UBat) / BattLowVoltageWarning;
if(StickGasHover < 70) StickGasHover = 70;
else if(StickGasHover > 150) StickGasHover = 150;
}
}
if(BaroExpandActive) SollHoehe = HoehenWert; // update setpoint to current altitude if Expanding is active
} //if FCFlags & MKFCFLAG_FLY
else
{
SollHoehe = HoehenWert - 400;
if(EE_Parameter.Hoehe_StickNeutralPoint) StickGasHover = EE_Parameter.Hoehe_StickNeutralPoint;
else StickGasHover = 120;
HoverGas = GasMischanteil;
VarioCharacter = '.';
}
HCGas = HoverGas; // take hover gas (neutral point)
}
if(HoehenWert > SollHoehe || !(Parameter_ExtraConfig & CFG2_HEIGHT_LIMIT))
{
// from this point the Heigth Control Algorithm is identical for both versions
if(BaroExpandActive) // baro range expanding active
{
HCGas = HoverGas; // hover while expanding baro adc range
HeightDeviation = 0;
} // EOF // baro range expanding active
else // valid data from air pressure sensor
{
// ------------------------- P-Part ----------------------------
tmp_long = (HoehenWert - SollHoehe); // positive when too high
LIMIT_MIN_MAX(tmp_long, -32767L, 32767L); // avoid overflov when casting to int16_t
HeightDeviation = (int)(tmp_long); // positive when too high
tmp_long = (tmp_long * (long)Parameter_Hoehe_P) / 32L; // p-part
LIMIT_MIN_MAX(tmp_long, -127 * STICK_GAIN, 256 * STICK_GAIN); // more than the full range makes no sense
GasReduction = tmp_long;
// ------------------------- D-Part 1: Vario Meter ----------------------------
tmp_int = VarioMeter / 8;
LIMIT_MIN_MAX(tmp_int, -127, 128);
tmp_int = (tmp_int * (long)Parameter_Luftdruck_D) / 4L; // scale to d-gain parameter
LIMIT_MIN_MAX(tmp_int,-64 * STICK_GAIN, 64 * STICK_GAIN);
if(FC_StatusFlags & (FC_STATUS_VARIO_TRIM_UP|FC_STATUS_VARIO_TRIM_DOWN)) tmp_int /= 4; // reduce d-part while trimming setpoint
else
if(Parameter_ExtraConfig & CFG2_HEIGHT_LIMIT) tmp_int /= 8; // reduce d-part in "Deckel" mode
GasReduction += tmp_int;
} // EOF no baro range expanding
// ------------------------ D-Part 2: ACC-Z Integral ------------------------
if(Parameter_Hoehe_ACC_Wirkung)
{
tmp_long = ((Mess_Integral_Hoch / 128L) * (int32_t) Parameter_Hoehe_ACC_Wirkung) / (128L / STICK_GAIN);
LIMIT_MIN_MAX(tmp_long, -32 * STICK_GAIN, 64 * STICK_GAIN);
GasReduction += tmp_long;
}
// ------------------------ D-Part 3: GpsZ ----------------------------------
tmp_int = (Parameter_Hoehe_GPS_Z * (int)FromNaviCtrl_Value.GpsZ)/128L;
LIMIT_MIN_MAX(tmp_int, -32 * STICK_GAIN, 64 * STICK_GAIN);
GasReduction += tmp_int;
GasReduction = (long)((long)GasReduction * HoverGas) / 512; // scale to the gas value
// ------------------------ ----------------------------------
HCGas -= GasReduction;
// limit deviation from hoover point within the target region
if(!AltitudeSetpointTrimming && HoverGas > 0) // height setpoint is not changed and hoover gas not zero
{
unsigned int tmp;
tmp = abs(HeightDeviation);
if(tmp <= 60)
{
LIMIT_MIN_MAX(HCGas, HoverGasMin, HoverGasMax); // limit gas around the hoover point
}
else
{
tmp = (tmp - 60) / 32;
if(tmp > 15) tmp = 15;
if(HeightDeviation > 0)
{
tmp = (HoverGasMin * (16 - tmp)) / 16;
LIMIT_MIN_MAX(HCGas, tmp, HoverGasMax); // limit gas around the hoover point
}
else
{
tmp = (HoverGasMax * (tmp + 16)) / 16;
LIMIT_MIN_MAX(HCGas, HoverGasMin, tmp); // limit gas around the hoover point
}
}
}
// strech control output by inverse attitude projection 1/cos
// + 1/cos(angle) ++++++++++++++++++++++++++
tmp_long2 = (int32_t)HCGas;
tmp_long2 *= 8192L;
tmp_long2 /= CosAttitude;
HCGas = (int16_t)tmp_long2;
// update height control gas averaging
FilterHCGas = (FilterHCGas * (HC_GAS_AVERAGE - 1) + HCGas) / HC_GAS_AVERAGE;
// limit height control gas pd-control output
LIMIT_MIN_MAX(FilterHCGas, EE_Parameter.Hoehe_MinGas * STICK_GAIN, (MAX_GAS - 20) * STICK_GAIN);
// set GasMischanteil to HeightControlGasFilter
if(Parameter_ExtraConfig & CFG2_HEIGHT_LIMIT)
{ // old version
LIMIT_MAX(FilterHCGas, GasMischanteil); // nicht mehr als Gas
GasMischanteil = FilterHCGas;
}
else GasMischanteil = FilterHCGas + (GasMischanteil - HoverGas) / 4; // only in Vario-Mode
}
}// EOF height control active
else // HC not active
{
//update hoover gas stick value when HC is not active
if(!EE_Parameter.Hoehe_StickNeutralPoint)
{
StickGasHover = HoverGas/STICK_GAIN; // rescale back to stick value
StickGasHover = (StickGasHover * UBat) / BattLowVoltageWarning;
}
else StickGasHover = EE_Parameter.Hoehe_StickNeutralPoint;
LIMIT_MIN_MAX(StickGasHover, 70, 150); // reserve some range for trim up and down
FilterHCGas = GasMischanteil;
// set both flags to indicate no vario mode
FC_StatusFlags |= (FC_STATUS_VARIO_TRIM_UP|FC_STATUS_VARIO_TRIM_DOWN);
FC_StatusFlags2 &= ~FC_STATUS2_ALTITUDE_CONTROL;
}
// Hover gas estimation by averaging gas control output on small z-velocities
// this is done only if height contol option is selected in global config and aircraft is flying
if((FC_StatusFlags & FC_STATUS_FLY))// && !(FC_SatusFlags & FC_STATUS_EMERGENCY_LANDING))
{
if(HoverGasFilter == 0 || StartTrigger == 1) HoverGasFilter = HOVER_GAS_AVERAGE * (unsigned long)(GasMischanteil); // init estimation
if(StartTrigger == 1) StartTrigger = 2;
tmp_long2 = (int32_t)GasMischanteil; // take current thrust
tmp_long2 *= CosAttitude; // apply attitude projection
tmp_long2 /= 8192;
// average vertical projected thrust
if(modell_fliegt < 4000) // the first 8 seconds
{ // reduce the time constant of averaging by factor of 4 to get much faster a stable value
HoverGasFilter -= HoverGasFilter/(HOVER_GAS_AVERAGE/16L);
HoverGasFilter += 16L * tmp_long2;
}
if(modell_fliegt < 8000) // the first 16 seconds
{ // reduce the time constant of averaging by factor of 2 to get much faster a stable value
HoverGasFilter -= HoverGasFilter/(HOVER_GAS_AVERAGE/4L);
HoverGasFilter += 4L * tmp_long2;
}
else //later
if(abs(VarioMeter) < 100 && abs(HoehenWert - SollHoehe) < 256) // only on small vertical speed & difference is small (only descending)
{
HoverGasFilter -= HoverGasFilter/HOVER_GAS_AVERAGE;
HoverGasFilter += tmp_long2;
}
HoverGas = (int16_t)(HoverGasFilter/HOVER_GAS_AVERAGE);
if(EE_Parameter.Hoehe_HoverBand)
{
int16_t band;
band = HoverGas / EE_Parameter.Hoehe_HoverBand; // the higher the parameter the smaller the range
HoverGasMin = HoverGas - band;
HoverGasMax = HoverGas + band;
}
else
{ // no limit
HoverGasMin = 0;
HoverGasMax = 1023;
}
}
else
{
StartTrigger = 0;
HoverGasFilter = 0;
HoverGas = 0;
}
}// EOF Parameter_GlobalConfig & CFG_HEIGHT_CONTROL
else
{
// set undefined state to indicate vario off
FC_StatusFlags |= (FC_STATUS_VARIO_TRIM_UP|FC_STATUS_VARIO_TRIM_DOWN);
} // EOF no height control
 
// Linits the maximum gas in case of "Out of Range emergency landing"
if(NC_To_FC_Flags & NC_TO_FC_EMERGENCY_LANDING)
{
if(GasMischanteil/STICK_GAIN > HooverGasEmergencyPercent && HoverGas) GasMischanteil = HooverGasEmergencyPercent * STICK_GAIN;
SollHoehe = HoehenWert; // update setpoint to current heigth
beeptime = 15000;
BeepMuster = 0x0E00;
}
// limit gas to parameter setting
LIMIT_MIN(GasMischanteil, (MIN_GAS + 10) * STICK_GAIN);
if(GasMischanteil > (MAX_GAS - 20) * STICK_GAIN) GasMischanteil = (MAX_GAS - 20) * STICK_GAIN;
 
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// all BL-Ctrl connected?
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if(MissingMotor || Capacity.MinOfMaxPWM != 255 || NC_ErrorCode) // wait until all BL-Ctrls started and no Errors
if(modell_fliegt > 1 && modell_fliegt < 50 && GasMischanteil > 0) // only during start-phase
{
modell_fliegt = 1;
GasMischanteil = (MIN_GAS + 10) * STICK_GAIN;
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Mischer und PI-Regler
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
DebugOut.Analog[7] = GasMischanteil;
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Gier-Anteil
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
GierMischanteil = MesswertGier - sollGier * STICK_GAIN; // Regler für Gier
#define MIN_GIERGAS (40*STICK_GAIN) // unter diesem Gaswert trotzdem Gieren
if(GasMischanteil > MIN_GIERGAS)
{
if(GierMischanteil > (GasMischanteil / 2)) GierMischanteil = GasMischanteil / 2;
if(GierMischanteil < -(GasMischanteil / 2)) GierMischanteil = -(GasMischanteil / 2);
}
else
{
if(GierMischanteil > (MIN_GIERGAS / 2)) GierMischanteil = MIN_GIERGAS / 2;
if(GierMischanteil < -(MIN_GIERGAS / 2)) GierMischanteil = -(MIN_GIERGAS / 2);
}
tmp_int = MAX_GAS*STICK_GAIN;
if(GierMischanteil > ((tmp_int - GasMischanteil))) GierMischanteil = ((tmp_int - GasMischanteil));
if(GierMischanteil < -((tmp_int - GasMischanteil))) GierMischanteil = -((tmp_int - GasMischanteil));
 
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Nick-Achse
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
DiffNick = MesswertNick - StickNick; // Differenz bestimmen
if(IntegralFaktor) SummeNick += IntegralNickMalFaktor - StickNick; // I-Anteil bei Winkelregelung
else SummeNick += DiffNick; // I-Anteil bei HH
if(SummeNick > (STICK_GAIN * 16000L)) SummeNick = (STICK_GAIN * 16000L);
if(SummeNick < -(16000L * STICK_GAIN)) SummeNick = -(16000L * STICK_GAIN);
 
if(EE_Parameter.Gyro_Stability <= 8) pd_ergebnis_nick = (EE_Parameter.Gyro_Stability * DiffNick) / 8; // PI-Regler für Nick
else pd_ergebnis_nick = ((EE_Parameter.Gyro_Stability / 2) * DiffNick) / 4; // Überlauf verhindern
pd_ergebnis_nick += SummeNick / Ki;
 
tmp_int = (long)((long)Parameter_DynamicStability * (long)(GasMischanteil + abs(GierMischanteil)/2)) / 64;
if(pd_ergebnis_nick > tmp_int) pd_ergebnis_nick = tmp_int;
if(pd_ergebnis_nick < -tmp_int) pd_ergebnis_nick = -tmp_int;
 
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Roll-Achse
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
DiffRoll = MesswertRoll - StickRoll; // Differenz bestimmen
if(IntegralFaktor) SummeRoll += IntegralRollMalFaktor - StickRoll;// I-Anteil bei Winkelregelung
else SummeRoll += DiffRoll; // I-Anteil bei HH
if(SummeRoll > (STICK_GAIN * 16000L)) SummeRoll = (STICK_GAIN * 16000L);
if(SummeRoll < -(16000L * STICK_GAIN)) SummeRoll = -(16000L * STICK_GAIN);
 
if(EE_Parameter.Gyro_Stability <= 8) pd_ergebnis_roll = (EE_Parameter.Gyro_Stability * DiffRoll) / 8; // PI-Regler für Roll
else pd_ergebnis_roll = ((EE_Parameter.Gyro_Stability / 2) * DiffRoll) / 4; // Überlauf verhindern
pd_ergebnis_roll += SummeRoll / Ki;
tmp_int = (long)((long)Parameter_DynamicStability * (long)(GasMischanteil + abs(GierMischanteil)/2)) / 64;
if(pd_ergebnis_roll > tmp_int) pd_ergebnis_roll = tmp_int;
if(pd_ergebnis_roll < -tmp_int) pd_ergebnis_roll = -tmp_int;
 
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Universal Mixer
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
for(i=0; i<MAX_MOTORS; i++)
{
signed int tmp_int;
if(Mixer.Motor[i][0] > 0)
{
// Gas
if(Mixer.Motor[i][0] == 64) tmp_int = GasMischanteil; else tmp_int = ((long)GasMischanteil * Mixer.Motor[i][0]) / 64L;
// Nick
if(Mixer.Motor[i][1] == 64) tmp_int += pd_ergebnis_nick;
else if(Mixer.Motor[i][1] == -64) tmp_int -= pd_ergebnis_nick;
else tmp_int += ((long)pd_ergebnis_nick * Mixer.Motor[i][1]) / 64L;
// Roll
if(Mixer.Motor[i][2] == 64) tmp_int += pd_ergebnis_roll;
else if(Mixer.Motor[i][2] == -64) tmp_int -= pd_ergebnis_roll;
else tmp_int += ((long)pd_ergebnis_roll * Mixer.Motor[i][2]) / 64L;
// Gier
if(Mixer.Motor[i][3] == 64) tmp_int += GierMischanteil;
else if(Mixer.Motor[i][3] == -64) tmp_int -= GierMischanteil;
else tmp_int += ((long)GierMischanteil * Mixer.Motor[i][3]) / 64L;
 
if(tmp_int > tmp_motorwert[i]) tmp_int = (tmp_motorwert[i] + tmp_int) / 2; // MotorSmoothing
// else tmp_int = 2 * tmp_int - tmp_motorwert[i]; // original MotorSmoothing
else
{
if(EE_Parameter.MotorSmooth == 0)
{
tmp_int = 2 * tmp_int - tmp_motorwert[i]; // original MotorSmoothing
}
else // 1 means tmp_int = tmp_int;
if(EE_Parameter.MotorSmooth > 1)
{
// If >= 2 then allow >= 50% of the intended step down to rapidly reach the intended value.
tmp_int = tmp_int + ((tmp_motorwert[i] - tmp_int)/EE_Parameter.MotorSmooth);
}
}
 
LIMIT_MIN_MAX(tmp_int,(int) MIN_GAS * 4,(int) MAX_GAS * 4);
Motor[i].SetPoint = tmp_int / 4;
Motor[i].SetPointLowerBits = (tmp_int % 4)<<1; // (3 bits total)
tmp_motorwert[i] = tmp_int;
}
else
{
Motor[i].SetPoint = 0;
Motor[i].SetPointLowerBits = 0;
}
}
}
//DebugOut.Analog[16]
/branches/V0.88n S.BUS ATmega644 tempolo/main.c
0,0 → 1,424
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + www.MikroKopter.com
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Software Nutzungsbedingungen (english version: see below)
// + der Fa. HiSystems GmbH, Flachsmeerstrasse 2, 26802 Moormerland - nachfolgend Lizenzgeber genannt -
// + Der Lizenzgeber räumt dem Kunden ein nicht-ausschließliches, zeitlich und räumlich* unbeschränktes Recht ein, die im den
// + Mikrocontroller verwendete Firmware für die Hardware Flight-Ctrl, Navi-Ctrl, BL-Ctrl, MK3Mag & PC-Programm MikroKopter-Tool
// + - nachfolgend Software genannt - nur für private Zwecke zu nutzen.
// + Der Einsatz dieser Software ist nur auf oder mit Produkten des Lizenzgebers zulässig.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Die vom Lizenzgeber gelieferte Software ist urheberrechtlich geschützt. Alle Rechte an der Software sowie an sonstigen im
// + Rahmen der Vertragsanbahnung und Vertragsdurchführung überlassenen Unterlagen stehen im Verhältnis der Vertragspartner ausschließlich dem Lizenzgeber zu.
// + Die in der Software enthaltenen Copyright-Vermerke, Markenzeichen, andere Rechtsvorbehalte, Seriennummern sowie
// + sonstige der Programmidentifikation dienenden Merkmale dürfen vom Kunden nicht verändert oder unkenntlich gemacht werden.
// + Der Kunde trifft angemessene Vorkehrungen für den sicheren Einsatz der Software. Er wird die Software gründlich auf deren
// + Verwendbarkeit zu dem von ihm beabsichtigten Zweck testen, bevor er diese operativ einsetzt.
// + Die Haftung des Lizenzgebers wird - soweit gesetzlich zulässig - begrenzt in Höhe des typischen und vorhersehbaren
// + Schadens. Die gesetzliche Haftung bei Personenschäden und nach dem Produkthaftungsgesetz bleibt unberührt. Dem Lizenzgeber steht jedoch der Einwand
// + des Mitverschuldens offen.
// + Der Kunde trifft angemessene Vorkehrungen für den Fall, dass die Software ganz oder teilweise nicht ordnungsgemäß arbeitet.
// + Er wird die Software gründlich auf deren Verwendbarkeit zu dem von ihm beabsichtigten Zweck testen, bevor er diese operativ einsetzt.
// + Der Kunde wird er seine Daten vor Einsatz der Software nach dem Stand der Technik sichern.
// + Der Kunde ist darüber unterrichtet, dass der Lizenzgeber seine Daten im zur Vertragsdurchführung erforderlichen Umfang
// + und auf Grundlage der Datenschutzvorschriften erhebt, speichert, verarbeitet und, sofern notwendig, an Dritte übermittelt.
// + *) Die räumliche Nutzung bezieht sich nur auf den Einsatzort, nicht auf die Reichweite der programmierten Software.
// + #### ENDE DER NUTZUNGSBEDINGUNGEN ####'
// + Hinweis: Informationen über erweiterte Nutzungsrechte (wie z.B. Nutzung für nicht-private Zwecke) sind auf Anfrage per Email an info(@)hisystems.de verfügbar.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Software LICENSING TERMS
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + of HiSystems GmbH, Flachsmeerstrasse 2, 26802 Moormerland, Germany - the Licensor -
// + The Licensor grants the customer a non-exclusive license to use the microcontroller firmware of the Flight-Ctrl, Navi-Ctrl, BL-Ctrl, and MK3Mag hardware
// + (the Software) exclusively for private purposes. The License is unrestricted with respect to time and territory*.
// + The Software may only be used with the Licensor's products.
// + The Software provided by the Licensor is protected by copyright. With respect to the relationship between the parties to this
// + agreement, all rights pertaining to the Software and other documents provided during the preparation and execution of this
// + agreement shall be the property of the Licensor.
// + The information contained in the Software copyright notices, trademarks, other legal reservations, serial numbers and other
// + features that can be used to identify the program may not be altered or defaced by the customer.
// + The customer shall be responsible for taking reasonable precautions
// + for the safe use of the Software. The customer shall test the Software thoroughly regarding its suitability for the
// + intended purpose before implementing it for actual operation. The Licensor's liability shall be limited to the extent of typical and
// + foreseeable damage to the extent permitted by law, notwithstanding statutory liability for bodily injury and product
// + liability. However, the Licensor shall be entitled to the defense of contributory negligence.
// + The customer will take adequate precautions in the case, that the software is not working properly. The customer will test
// + the software for his purpose before any operational usage. The customer will backup his data before using the software.
// + The customer understands that the Licensor collects, stores and processes, and, where required, forwards, customer data
// + to third parties to the extent necessary for executing the agreement, subject to applicable data protection and privacy regulations.
// + *) The territory aspect only refers to the place where the Software is used, not its programmed range.
// + #### END OF LICENSING TERMS ####
// + Note: For information on license extensions (e.g. commercial use), please contact us at info(@)hisystems.de.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#include "main.h"
unsigned char DisableRcOffBeeping = 0;
unsigned char PlatinenVersion = 10;
unsigned char BattLowVoltageWarning = 94;
unsigned int FlugMinuten = 0,FlugMinutenGesamt = 0;
unsigned int FlugSekunden = 0;
pVoidFnct_pVoidFnctChar_const_fmt _printf_P;
unsigned char FoundMotors = 0;
unsigned char JetiBeep = 0; // to allow any Morse-Beeping of the Jeti-Box
 
void PrintLine(void)
{
printf("\n\r===================================");
}
 
 
void CalMk3Mag(void)
{
static unsigned char stick = 1;
if(PPM_in[EE_Parameter.Kanalbelegung[K_NICK]] > -20) stick = 0;
if((PPM_in[EE_Parameter.Kanalbelegung[K_NICK]] < -70) && !stick)
{
stick = 1;
WinkelOut.CalcState++;
if(WinkelOut.CalcState > 4)
{
// WinkelOut.CalcState = 0; // in Uart.c
beeptime = 1000;
}
else Piep(WinkelOut.CalcState,150);
}
DebugOut.Analog[19] = WinkelOut.CalcState;
}
 
 
void LipoDetection(unsigned char print)
{
#define MAX_CELL_VOLTAGE 43 // max cell volatage for LiPO
unsigned int timer, cells;
if(print) printf("\n\rBatt:");
if(EE_Parameter.UnterspannungsWarnung < 50) // automatische Zellenerkennung
{
timer = SetDelay(500);
if(print) while (!CheckDelay(timer));
// up to 6s LiPo, less than 2s is technical impossible
for(cells = 2; cells < 7; cells++)
{
if(UBat < cells * MAX_CELL_VOLTAGE) break;
}
 
BattLowVoltageWarning = cells * EE_Parameter.UnterspannungsWarnung;
if(print)
{
Piep(cells, 200);
printf(" %d Cells ", cells);
}
}
else BattLowVoltageWarning = EE_Parameter.UnterspannungsWarnung;
if(print) printf(" Low warning: %d.%d",BattLowVoltageWarning/10,BattLowVoltageWarning%10);
}
 
//############################################################################
//Hauptprogramm
int main (void)
//############################################################################
{
unsigned int timer,i,timer2 = 0, timerPolling;
 
DDRB = 0x00;
PORTB = 0x00;
for(timer = 0; timer < 1000; timer++); // verzögern
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
PlatinenVersion = 21;
#else
if(PINB & 0x01)
{
if(PINB & 0x02) PlatinenVersion = 13;
else PlatinenVersion = 11;
}
else
{
if(PINB & 0x02) PlatinenVersion = 20;
else PlatinenVersion = 10;
}
#endif
DDRC = 0x81; // SCL
DDRC |=0x40; // HEF4017 Reset
PORTC = 0xff; // Pullup SDA
DDRB = 0x1B; // LEDs und Druckoffset
PORTB = 0x01; // LED_Rot
DDRD = 0x3E; // Speaker & TXD & J3 J4 J5
PORTD = 0x47; // LED
HEF4017Reset_ON;
MCUSR &=~(1<<WDRF);
WDTCSR |= (1<<WDCE)|(1<<WDE);
WDTCSR = 0;
 
beeptime = 2500;
StickGier = 0; PPM_in[K_GAS] = 0; StickRoll = 0; StickNick = 0;
if(PlatinenVersion >= 20) GIER_GRAD_FAKTOR = 1220; else GIER_GRAD_FAKTOR = 1291; // unterschiedlich für ME und ENC
ROT_OFF;
 
Timer_Init();
TIMER2_Init();
UART_Init();
rc_sum_init();
ADC_Init();
I2C_Init(1);
SPI_MasterInit();
Capacity_Init();
LIBFC_Init();
GRN_ON;
sei();
ParamSet_Init();
 
 
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Check connected BL-Ctrls
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Check connected BL-Ctrls
BLFlags |= BLFLAG_READ_VERSION;
motor_read = 0; // read the first I2C-Data
SendMotorData();
timer = SetDelay(500);
while(!(BLFlags & BLFLAG_TX_COMPLETE) && !CheckDelay(timer)); //wait for complete transfer
 
printf("\n\rFound BL-Ctrl: ");
timer = SetDelay(4000);
for(i=0; i < MAX_MOTORS; i++)
{
SendMotorData();
while(!(BLFlags & BLFLAG_TX_COMPLETE) && !CheckDelay(timer)); //wait for complete transfer
if(Mixer.Motor[i][0] > 0) // wait max 4 sec for the BL-Ctrls to wake up
{
while(!CheckDelay(timer) && !(Motor[i].State & MOTOR_STATE_PRESENT_MASK) )
{
SendMotorData();
while(!(BLFlags & BLFLAG_TX_COMPLETE) && !CheckDelay(timer)); //wait for complete transfer
}
}
if(Motor[i].State & MOTOR_STATE_PRESENT_MASK)
{
printf("%d",i+1);
FoundMotors++;
// if(Motor[i].Version & MOTOR_STATE_NEW_PROTOCOL_MASK) printf("(new) ");
}
}
for(i=0; i < MAX_MOTORS; i++)
{
if(!(Motor[i].State & MOTOR_STATE_PRESENT_MASK) && Mixer.Motor[i][0] > 0)
{
printf("\n\r\n\r!! MISSING BL-CTRL: %d !!",i+1);
ServoActive = 2; // just in case the FC would be used as camera-stabilizer
}
Motor[i].State &= ~MOTOR_STATE_ERROR_MASK; // clear error counter
}
PrintLine();// ("\n\r===================================");
 
 
if(RequiredMotors < FoundMotors) VersionInfo.HardwareError[1] |= FC_ERROR1_MIXER;
 
//if(EE_Parameter.GlobalConfig & CFG_HOEHENREGELUNG)
{
printf("\n\rCalibrating pressure sensor..");
timer = SetDelay(1000);
SucheLuftruckOffset();
while (!CheckDelay(timer));
printf("OK\n\r");
}
 
SetNeutral(0);
 
ROT_OFF;
 
beeptime = 2000;
ExternControl.Digital[0] = 0x55;
 
 
FlugMinuten = (unsigned int)GetParamByte(PID_FLIGHT_MINUTES) * 256 + (unsigned int)GetParamByte(PID_FLIGHT_MINUTES + 1);
FlugMinutenGesamt = (unsigned int)GetParamByte(PID_FLIGHT_MINUTES_TOTAL) * 256 + (unsigned int)GetParamByte(PID_FLIGHT_MINUTES_TOTAL + 1);
 
if((FlugMinutenGesamt == 0xFFFF) || (FlugMinuten == 0xFFFF))
{
FlugMinuten = 0;
FlugMinutenGesamt = 0;
}
printf("\n\rFlight-time %u min Total:%u min", FlugMinuten, FlugMinutenGesamt);
 
LcdClear();
I2CTimeout = 5000;
WinkelOut.Orientation = 1;
LipoDetection(1);
LIBFC_ReceiverInit(EE_Parameter.Receiver);
PrintLine();// ("\n\r===================================");
//SpektrumBinding();
timer = SetDelay(2000);
timerPolling = SetDelay(250);
 
Debug(ANSI_CLEAR "FC-Start!\n\rFlugzeit: %d min", FlugMinutenGesamt); // Note: this won't waste flash memory, if #DEBUG is not active
DebugOut.Status[0] = 0x01 | 0x02;
JetiBeep = 0;
if(EE_Parameter.ExtraConfig & CFG_NO_RCOFF_BEEPING) DisableRcOffBeeping = 1;
while (1)
{
if(ReceiverUpdateModeActive) while (1) PORTC &= ~(1<<7); // Beeper off
 
//GRN_ON;
if(UpdateMotor && AdReady) // ReglerIntervall
{
//GRN_OFF;
UpdateMotor=0;
if(WinkelOut.CalcState) CalMk3Mag();
else MotorRegler();
SendMotorData();
ROT_OFF;
if(SenderOkay) { SenderOkay--; /*VersionInfo.HardwareError[1] &= ~FC_ERROR1_PPM;*/ }
else
{
TIMSK1 |= _BV(ICIE1); // enable PPM-Input
PPM_in[0] = 0; // set RSSI to zero on data timeout
VersionInfo.HardwareError[1] |= FC_ERROR1_PPM;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//if(HoehenReglerAktiv && NaviDataOkay && SenderOkay < 160 && SenderOkay > 10 && FromNaviCtrl_Value.SerialDataOkay > 220) SenderOkay = 160;
//if(HoehenReglerAktiv && NaviDataOkay && SenderOkay < 101 && SenderOkay > 10 && FromNaviCtrl_Value.SerialDataOkay > 1) SenderOkay = 101;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if(!--I2CTimeout || MissingMotor)
{
if(!I2CTimeout)
{
I2C_Reset();
I2CTimeout = 5;
DebugOut.Analog[28]++; // I2C-Error
VersionInfo.HardwareError[1] |= FC_ERROR1_I2C;
DebugOut.Status[1] |= 0x02; // BL-Error-Status
}
if((BeepMuster == 0xffff) && MotorenEin)
{
beeptime = 25000;
BeepMuster = 0x0080;
}
}
else
{
ROT_OFF;
}
LIBFC_Polling();
 
if(!UpdateMotor)
{
//#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
if(NewSBusData) ProcessSBus();
else
//#endif
{
if(CalculateServoSignals) CalculateServo();
DatenUebertragung();
BearbeiteRxDaten();
if(CheckDelay(timer))
{
static unsigned char second;
timer += 20; // 20 ms interval
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
if(EE_Parameter.Receiver == RECEIVER_HOTT) HoTT_Menu();
#endif
if(MissingMotor)
{
VersionInfo.HardwareError[1] |= FC_ERROR1_BL_MISSING;
DebugOut.Status[1] |= 0x02; // BL-Error-Status
}
else
{
if(!beeptime)
{
if(I2CTimeout > 6) DebugOut.Status[1] &= ~0x02; // BL-Error-Status
}
}
if(DisableRcOffBeeping) if(SenderOkay > 150) { DisableRcOffBeeping = 0; beeptime = 5000;};
if(PcZugriff) PcZugriff--;
else
{
ExternControl.Config = 0;
ExternStickNick = 0;
ExternStickRoll = 0;
ExternStickGier = 0;
if(!SenderOkay)
{
if(BeepMuster == 0xffff && DisableRcOffBeeping != 2)
{
beeptime = 15000;
BeepMuster = 0x0c00;
if(DisableRcOffBeeping) DisableRcOffBeeping = 2;
}
}
}
if(NaviDataOkay > 200)
{
NaviDataOkay--;
VersionInfo.HardwareError[1] &= ~FC_ERROR1_SPI_RX;
}
else
{
if(NC_Version.Compatible)
{
VersionInfo.HardwareError[1] |= FC_ERROR1_SPI_RX;
NC_ErrorCode = 9; // "ERR: no NC communication"
if(BeepMuster == 0xffff && MotorenEin)
{
beeptime = 15000;
BeepMuster = 0xA800;
}
}
GPS_Nick = 0;
GPS_Roll = 0;
GPS_Aid_StickMultiplikator = 0;
GPSInfo.Flags = 0;
FromNaviCtrl.AccErrorN = 0;
FromNaviCtrl.AccErrorR = 0;
FromNaviCtrl.CompassValue = -1;
NaviDataOkay = 0;
}
if(UBat < BattLowVoltageWarning)
{
FC_StatusFlags |= FC_STATUS_LOWBAT;
if(BeepMuster == 0xffff)
{
beeptime = 6000;
BeepMuster = 0x0300;
}
}
else if(!beeptime) FC_StatusFlags &= ~FC_STATUS_LOWBAT;
 
SPI_StartTransmitPacket();
SendSPI = 4;
// +++++++++++++++++++++++++++++++++
// Sekundentakt
if(++second == 49)
{
second = 0;
if(FC_StatusFlags & FC_STATUS_FLY) FlugSekunden++;
else
{
timer2 = 1450; // 0,5 Minuten aufrunden
if(StartLuftdruck < Luftdruck) StartLuftdruck++;
else
if(StartLuftdruck > Luftdruck) StartLuftdruck--;
}
}
// +++++++++++++++++++++++++++++++++
if(++timer2 == 2930) // eine Minute
{
timer2 = 0;
FlugMinuten++;
FlugMinutenGesamt++;
SetParamByte(PID_FLIGHT_MINUTES,FlugMinuten / 256);
SetParamByte(PID_FLIGHT_MINUTES+1,FlugMinuten % 256);
SetParamByte(PID_FLIGHT_MINUTES_TOTAL,FlugMinutenGesamt / 256);
SetParamByte(PID_FLIGHT_MINUTES_TOTAL+1,FlugMinutenGesamt % 256);
timer = SetDelay(20); // falls "timer += 20;" mal nicht geht
}
}
LED_Update();
Capacity_Update();
} //else DebugOut.Analog[26]++;
}
}
if(!SendSPI) { SPI_TransmitByte(); }
}
return (1);
}
//DebugOut.Analog[16]
 
/branches/V0.88n S.BUS ATmega644 tempolo/makefile
0,0 → 1,494
#--------------------------------------------------------------------
# MCU name
#MCU = atmega1284p
MCU = atmega644p
F_CPU = 20000000
#-------------------------------------------------------------------
VERSION_MAJOR = 0
VERSION_MINOR = 88
VERSION_PATCH = 13
VERSION_SERIAL_MAJOR = 11 # Serial Protocol
VERSION_SERIAL_MINOR = 0 # Serial Protocol
NC_SPI_COMPATIBLE = 51 # Navi-Kompatibilität
#-------------------------------------------------------------------
# ATMEGA644: 63487 is maximum
#-------------------------------------------------------------------#-------------------------------------------------------------------
# 0 a
# 1 b
# 2 c
# 3 d
# 4 e
# 5 f
# 6 g
# 7 h
# 8 i
# 9 j
# 10 k
# 11 L
#-------------------------------------------------------------------
 
# get SVN revision
REV := $(shell sh -c "cat .svn/entries | sed -n '4p'")
 
ifeq ($(MCU), atmega1284p)
FUSE_SETTINGS = -u -U lfuse:w:0xff:m -U hfuse:w:0xdf:m
HEX_NAME = MEGA1284P
LIBFC_EXT = 1284
endif
 
ifeq ($(MCU), atmega644p)
FUSE_SETTINGS = -u -U lfuse:w:0xff:m -U hfuse:w:0xdf:m
HEX_NAME = MEGA644
LIBFC_EXT = 644
endif
 
ifeq ($(F_CPU), 16000000)
QUARZ = 16MHZ
endif
 
ifeq ($(F_CPU), 20000000)
QUARZ = 20MHZ
endif
 
 
# Output format. (can be srec, ihex, binary)
FORMAT = ihex
 
# Target file name (without extension).
 
ifeq ($(VERSION_PATCH), 0)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)a_SVN$(REV)
endif
ifeq ($(VERSION_PATCH), 1)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)b_SVN$(REV)
endif
ifeq ($(VERSION_PATCH), 2)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)c_SVN$(REV)
endif
ifeq ($(VERSION_PATCH), 3)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)d_SVN$(REV)
endif
ifeq ($(VERSION_PATCH), 4)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)e_SVN$(REV)
endif
ifeq ($(VERSION_PATCH), 5)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)f_SVN$(REV)
endif
ifeq ($(VERSION_PATCH), 6)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)g_SVN$(REV)
endif
ifeq ($(VERSION_PATCH), 7)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)h_SVN$(REV)
endif
ifeq ($(VERSION_PATCH), 8)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)i_SVN$(REV)
endif
ifeq ($(VERSION_PATCH), 9)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)j_SVN$(REV)
endif
ifeq ($(VERSION_PATCH), 10)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)k_SVN$(REV)
endif
ifeq ($(VERSION_PATCH), 11)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)L_SVN$(REV)
endif
ifeq ($(VERSION_PATCH), 12)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)m_SVN$(REV)
endif
ifeq ($(VERSION_PATCH), 13)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)n_SVN$(REV)
endif
ifeq ($(VERSION_PATCH), 14)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)o_SVN$(REV)
endif
ifeq ($(VERSION_PATCH), 15)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)p_SVN$(REV)
endif
ifeq ($(VERSION_PATCH), 16)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)q_SVN$(REV)
endif
ifeq ($(VERSION_PATCH), 17)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)r_SVN$(REV)
endif
ifeq ($(VERSION_PATCH), 18)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)s_SVN$(REV)
endif
ifeq ($(VERSION_PATCH), 19)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)t_SVN$(REV)
endif
ifeq ($(VERSION_PATCH), 20)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)u_SVN$(REV)
endif
ifeq ($(VERSION_PATCH), 21)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)v_SVN$(REV)
endif
ifeq ($(VERSION_PATCH), 22)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)w_SVN$(REV)
endif
ifeq ($(VERSION_PATCH), 23)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)x_SVN$(REV)
endif
ifeq ($(VERSION_PATCH), 24)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)y_SVN$(REV)
endif
ifeq ($(VERSION_PATCH), 25)
TARGET = Flight-Ctrl_$(HEX_NAME)_V$(VERSION_MAJOR)_$(VERSION_MINOR)z_SVN$(REV)
endif
 
 
# Optimization level, can be [0, 1, 2, 3, s]. 0 turns off optimization.
# (Note: 3 is not always the best optimization level. See avr-libc FAQ.)
OPT = s
#OPT = 2
 
##########################################################################################################
# List C source files here. (C dependencies are automatically generated.)
SRC = main.c uart.c timer0.c analog.c menu.c eeprom.c
SRC += twimaster.c rc.c fc.c GPS.c spi.c led.c Spektrum.c
SRC += mymath.c jetimenu.c capacity.c debug.c
SRC += hottmenu.c sbus.c user_receiver.c
##########################################################################################################
 
 
# List Assembler source files here.
# Make them always end in a capital .S. Files ending in a lowercase .s
# will not be considered source files but generated files (assembler
# output from the compiler), and will be deleted upon "make clean"!
# Even though the DOS/Win* filesystem matches both .s and .S the same,
# it will preserve the spelling of the filenames, and gcc itself does
# care about how the name is spelled on its command-line.
ASRC = isqrt.S
 
 
 
# List any extra directories to look for include files here.
# Each directory must be seperated by a space.
EXTRAINCDIRS =
 
 
# Optional compiler flags.
# -g: generate debugging information (for GDB, or for COFF conversion)
# -O*: optimization level
# -f...: tuning, see gcc manual and avr-libc documentation
# -Wall...: warning level
# -Wa,...: tell GCC to pass this to the assembler.
# -ahlms: create assembler listing
CFLAGS = -O$(OPT) -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -Wall -Wstrict-prototypes -Wa,-adhlns=$(<:%.c=%.lst) $(patsubst %,-I%,$(EXTRAINCDIRS))
 
 
# Set a "language standard" compiler flag.
# Unremark just one line below to set the language standard to use.
# gnu99 = C99 + GNU extensions. See GCC manual for more information.
#CFLAGS += -std=c89
#CFLAGS += -std=gnu89
#CFLAGS += -std=c99
CFLAGS += -std=gnu99
 
# shrink code size
CFLAGS += -mtiny-stack
#CFLAGS += -fno-inline-functions
CFLAGS += -mcall-prologues
 
CFLAGS += -DF_CPU=$(F_CPU) -DVERSION_MAJOR=$(VERSION_MAJOR) -DVERSION_MINOR=$(VERSION_MINOR) -DVERSION_PATCH=$(VERSION_PATCH) -DVERSION_SERIAL_MAJOR=$(VERSION_SERIAL_MAJOR) -DVERSION_SERIAL_MINOR=$(VERSION_SERIAL_MINOR) -DNC_SPI_COMPATIBLE=$(NC_SPI_COMPATIBLE)
 
 
# Optional assembler flags.
# -Wa,...: tell GCC to pass this to the assembler.
# -ahlms: create listing
# -gstabs: have the assembler create line number information; note that
# for use in COFF files, additional information about filenames
# and function names needs to be present in the assembler source
# files -- see avr-libc docs [FIXME: not yet described there]
ASFLAGS = -Wa,-adhlns=$(<:.S=.lst),-gstabs
 
 
 
# Optional linker flags.
# -Wl,...: tell GCC to pass this to linker.
# -Map: create map file
# --cref: add cross reference to map file
LDFLAGS = -Wl,-Map=$(TARGET).map,--cref
 
# Additional libraries
 
# Minimalistic printf version
#LDFLAGS += -Wl,-u,vfprintf -lprintf_min
 
# Floating point printf version (requires -lm below)
#LDFLAGS += -Wl,-u,vfprintf -lprintf_flt
 
# -lm = math library
LDFLAGS += -lm
 
LDFLAGS += libfc$(LIBFC_EXT).a
 
##LDFLAGS += -T./linkerfile/avr5.x
 
 
 
# Programming support using avrdude. Settings and variables.
 
# Programming hardware: alf avr910 avrisp bascom bsd
# dt006 pavr picoweb pony-stk200 sp12 stk200 stk500
#
# Type: avrdude -c ?
# to get a full listing.
#
#AVRDUDE_PROGRAMMER = dt006
#AVRDUDE_PROGRAMMER = stk200
#AVRDUDE_PROGRAMMER = ponyser
AVRDUDE_PROGRAMMER = avrispv2
#falls Ponyser ausgewählt wird, muss sich unsere avrdude-Configdatei im Bin-Verzeichnis des Compilers befinden
 
#AVRDUDE_PORT = com1 # programmer connected to serial device
#AVRDUDE_PORT = lpt1 # programmer connected to parallel port
AVRDUDE_PORT = usb # programmer connected to USB
 
#AVRDUDE_WRITE_FLASH = -U flash:w:$(TARGET).hex
AVRDUDE_WRITE_FLASH = -U flash:w:$(TARGET).hex $(FUSE_SETTINGS)
#AVRDUDE_WRITE_EEPROM = -U eeprom:w:$(TARGET).eep
 
#avrdude -c avrispv2 -P usb -p m32 -U flash:w:blink.hex
AVRDUDE_FLAGS = -p $(MCU) -P $(AVRDUDE_PORT) -c $(AVRDUDE_PROGRAMMER)
 
# Uncomment the following if you want avrdude's erase cycle counter.
# Note that this counter needs to be initialized first using -Yn,
# see avrdude manual.
#AVRDUDE_ERASE += -y
 
# Uncomment the following if you do /not/ wish a verification to be
# performed after programming the device.
AVRDUDE_FLAGS += -V
 
# Increase verbosity level. Please use this when submitting bug
# reports about avrdude. See <http://savannah.nongnu.org/projects/avrdude>
# to submit bug reports.
#AVRDUDE_FLAGS += -v -v
 
# ---------------------------------------------------------------------------
# Define directories, if needed.
DIRAVR = c:/winavr
DIRAVRBIN = $(DIRAVR)/bin
DIRAVRUTILS = $(DIRAVR)/utils/bin
DIRINC = .
DIRLIB = $(DIRAVR)/avr/lib
 
 
# Define programs and commands.
SHELL = sh
 
CC = avr-gcc
 
OBJCOPY = avr-objcopy
OBJDUMP = avr-objdump
SIZE = avr-size
 
# Programming support using avrdude.
AVRDUDE = avrdude
 
REMOVE = rm -f
COPY = cp
 
HEXSIZE = $(SIZE) --target=$(FORMAT) $(TARGET).hex
ELFSIZE = $(SIZE) -x -A $(TARGET).elf
LIMITS = $(SIZE) --mcu=$(MCU) -C $(TARGET).elf
 
 
# Define Messages
# English
MSG_ERRORS_NONE = Errors: none
MSG_BEGIN = -------- begin --------
MSG_END = -------- end --------
MSG_SIZE_BEFORE = Size before:
MSG_SIZE_AFTER = Size after:
MSG_COFF = Converting to AVR COFF:
MSG_EXTENDED_COFF = Converting to AVR Extended COFF:
MSG_FLASH = Creating load file for Flash:
MSG_EEPROM = Creating load file for EEPROM:
MSG_EXTENDED_LISTING = Creating Extended Listing:
MSG_SYMBOL_TABLE = Creating Symbol Table:
MSG_LINKING = Linking:
MSG_COMPILING = Compiling:
MSG_ASSEMBLING = Assembling:
MSG_CLEANING = Cleaning project:
 
 
# Define all object files.
OBJ = $(SRC:.c=.o) $(ASRC:.S=.o)
 
# Define all listing files.
LST = $(ASRC:.S=.lst) $(SRC:.c=.lst)
 
# Combine all necessary flags and optional flags.
# Add target processor to flags.
#ALL_CFLAGS = -mmcu=$(MCU) -DF_CPU=$(F_CPU) -I. $(CFLAGS)
ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS)
ALL_ASFLAGS = -mmcu=$(MCU) -I. -x assembler-with-cpp $(ASFLAGS)
 
 
# Default target.
all: begin gccversion sizebefore $(TARGET).elf $(TARGET).hex sizeafter finished end
 
 
# Eye candy.
# AVR Studio 3.x does not check make's exit code but relies on
# the following magic strings to be generated by the compile job.
begin:
@echo
@echo $(MSG_BEGIN)
 
finished:
@echo $(MSG_ERRORS_NONE)
 
end:
@echo $(MSG_END)
@echo
 
 
# Display size of file.
sizebefore:
@if [ -f $(TARGET).elf ]; then echo Size before:; $(ELFSIZE); $(HEXSIZE); $(LIMITS); echo; fi
sizeafter:
@if [ -f $(TARGET).elf ]; then echo Size after:; $(ELFSIZE); $(HEXSIZE); $(LIMITS); echo; fi
 
 
# Display compiler version information.
gccversion :
@$(CC) --version
 
 
# Convert ELF to COFF for use in debugging / simulating in
# AVR Studio or VMLAB.
COFFCONVERT=$(OBJCOPY) --debugging \
--change-section-address .data-0x800000 \
--change-section-address .bss-0x800000 \
--change-section-address .noinit-0x800000 \
--change-section-address .eeprom-0x810000
 
 
coff: $(TARGET).elf
@echo
@echo $(MSG_COFF) $(TARGET).cof
$(COFFCONVERT) -O coff-avr $< $(TARGET).cof
 
 
extcoff: $(TARGET).elf
@echo
@echo $(MSG_EXTENDED_COFF) $(TARGET).cof
$(COFFCONVERT) -O coff-ext-avr $< $(TARGET).cof
 
 
 
 
# Program the device.
program: $(TARGET).hex $(TARGET).eep
$(AVRDUDE) $(AVRDUDE_FLAGS) $(AVRDUDE_WRITE_FLASH) $(AVRDUDE_WRITE_EEPROM)
 
 
 
 
# Create final output files (.hex, .eep) from ELF output file.
%.hex: %.elf
@echo
@echo $(MSG_FLASH) $@
$(OBJCOPY) -O $(FORMAT) -R .eeprom $< $@
 
%.eep: %.elf
@echo
@echo $(MSG_EEPROM) $@
-$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \
--change-section-lma .eeprom=0 -O $(FORMAT) $< $@
 
# Create extended listing file from ELF output file.
%.lss: %.elf
@echo
@echo $(MSG_EXTENDED_LISTING) $@
$(OBJDUMP) -h -S $< > $@
 
# Create a symbol table from ELF output file.
%.sym: %.elf
@echo
@echo $(MSG_SYMBOL_TABLE) $@
avr-nm -n $< > $@
 
 
 
# Link: create ELF output file from object files.
.SECONDARY : $(TARGET).elf
.PRECIOUS : $(OBJ)
%.elf: $(OBJ)
@echo
@echo $(MSG_LINKING) $@
$(CC) $(ALL_CFLAGS) $(OBJ) --output $@ $(LDFLAGS)
 
 
# Compile: create object files from C source files.
%.o : %.c
@echo
@echo $(MSG_COMPILING) $<
$(CC) -c $(ALL_CFLAGS) $< -o $@
 
 
# Compile: create assembler files from C source files.
%.s : %.c
$(CC) -S $(ALL_CFLAGS) $< -o $@
 
 
# Assemble: create object files from assembler source files.
%.o : %.S
@echo
@echo $(MSG_ASSEMBLING) $<
$(CC) -c $(ALL_ASFLAGS) $< -o $@
 
 
 
 
 
 
# Target: clean project.
clean: begin clean_list finished end
 
clean_list :
@echo
@echo $(MSG_CLEANING)
$(REMOVE) Flight-Ctrl_*.hex
$(REMOVE) Flight-Ctrl_*.eep
$(REMOVE) $(TARGET).obj
$(REMOVE) $(TARGET).cof
$(REMOVE) Flight-Ctrl_*.elf
$(REMOVE) Flight-Ctrl_*.map
$(REMOVE) $(TARGET).obj
$(REMOVE) $(TARGET).a90
$(REMOVE) Flight-Ctrl_*.sym
$(REMOVE) $(TARGET).lnk
$(REMOVE) $(TARGET).lss
$(REMOVE) $(OBJ)
$(REMOVE) $(LST)
$(REMOVE) $(SRC:.c=.s)
$(REMOVE) $(SRC:.c=.d)
$(REMOVE) $(SRC:.c=.o)
 
 
# Automatically generate C source code dependencies.
# (Code originally taken from the GNU make user manual and modified
# (See README.txt Credits).)
#
# Note that this will work with sh (bash) and sed that is shipped with WinAVR
# (see the SHELL variable defined above).
# This may not work with other shells or other seds.
#
%.d: %.c
set -e; $(CC) -MM $(ALL_CFLAGS) $< \
| sed 's,\(.*\)\.o[ :]*,\1.o \1.d : ,g' > $@; \
[ -s $@ ] || rm -f $@
 
 
# Remove the '-' if you want to see the dependency files generated.
-include $(SRC:%.c=%.d)
 
 
 
# Listing of phony targets.
.PHONY : all begin finish end sizebefore sizeafter gccversion coff extcoff \
clean clean_list program
 
/branches/V0.88n S.BUS ATmega644 tempolo/sbus.c
0,0 → 1,200
/*#######################################################################################
Decodes the sbus protocol
#######################################################################################*/
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + www.MikroKopter.com
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Software Nutzungsbedingungen (english version: see below)
// + der Fa. HiSystems GmbH, Flachsmeerstrasse 2, 26802 Moormerland - nachfolgend Lizenzgeber genannt -
// + Der Lizenzgeber räumt dem Kunden ein nicht-ausschließliches, zeitlich und räumlich* unbeschränktes Recht ein, die im den
// + Mikrocontroller verwendete Firmware für die Hardware Flight-Ctrl, Navi-Ctrl, BL-Ctrl, MK3Mag & PC-Programm MikroKopter-Tool
// + - nachfolgend Software genannt - nur für private Zwecke zu nutzen.
// + Der Einsatz dieser Software ist nur auf oder mit Produkten des Lizenzgebers zulässig.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Die vom Lizenzgeber gelieferte Software ist urheberrechtlich geschützt. Alle Rechte an der Software sowie an sonstigen im
// + Rahmen der Vertragsanbahnung und Vertragsdurchführung überlassenen Unterlagen stehen im Verhältnis der Vertragspartner ausschließlich dem Lizenzgeber zu.
// + Die in der Software enthaltenen Copyright-Vermerke, Markenzeichen, andere Rechtsvorbehalte, Seriennummern sowie
// + sonstige der Programmidentifikation dienenden Merkmale dürfen vom Kunden nicht verändert oder unkenntlich gemacht werden.
// + Der Kunde trifft angemessene Vorkehrungen für den sicheren Einsatz der Software. Er wird die Software gründlich auf deren
// + Verwendbarkeit zu dem von ihm beabsichtigten Zweck testen, bevor er diese operativ einsetzt.
// + Die Haftung des Lizenzgebers wird - soweit gesetzlich zulässig - begrenzt in Höhe des typischen und vorhersehbaren
// + Schadens. Die gesetzliche Haftung bei Personenschäden und nach dem Produkthaftungsgesetz bleibt unberührt. Dem Lizenzgeber steht jedoch der Einwand
// + des Mitverschuldens offen.
// + Der Kunde trifft angemessene Vorkehrungen für den Fall, dass die Software ganz oder teilweise nicht ordnungsgemäß arbeitet.
// + Er wird die Software gründlich auf deren Verwendbarkeit zu dem von ihm beabsichtigten Zweck testen, bevor er diese operativ einsetzt.
// + Der Kunde wird er seine Daten vor Einsatz der Software nach dem Stand der Technik sichern.
// + Der Kunde ist darüber unterrichtet, dass der Lizenzgeber seine Daten im zur Vertragsdurchführung erforderlichen Umfang
// + und auf Grundlage der Datenschutzvorschriften erhebt, speichert, verarbeitet und, sofern notwendig, an Dritte übermittelt.
// + *) Die räumliche Nutzung bezieht sich nur auf den Einsatzort, nicht auf die Reichweite der programmierten Software.
// + #### ENDE DER NUTZUNGSBEDINGUNGEN ####'
// + Hinweis: Informationen über erweiterte Nutzungsrechte (wie z.B. Nutzung für nicht-private Zwecke) sind auf Anfrage per Email an info(@)hisystems.de verfügbar.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Software LICENSING TERMS
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + of HiSystems GmbH, Flachsmeerstrasse 2, 26802 Moormerland, Germany - the Licensor -
// + The Licensor grants the customer a non-exclusive license to use the microcontroller firmware of the Flight-Ctrl, Navi-Ctrl, BL-Ctrl, and MK3Mag hardware
// + (the Software) exclusively for private purposes. The License is unrestricted with respect to time and territory*.
// + The Software may only be used with the Licensor's products.
// + The Software provided by the Licensor is protected by copyright. With respect to the relationship between the parties to this
// + agreement, all rights pertaining to the Software and other documents provided during the preparation and execution of this
// + agreement shall be the property of the Licensor.
// + The information contained in the Software copyright notices, trademarks, other legal reservations, serial numbers and other
// + features that can be used to identify the program may not be altered or defaced by the customer.
// + The customer shall be responsible for taking reasonable precautions
// + for the safe use of the Software. The customer shall test the Software thoroughly regarding its suitability for the
// + intended purpose before implementing it for actual operation. The Licensor's liability shall be limited to the extent of typical and
// + foreseeable damage to the extent permitted by law, notwithstanding statutory liability for bodily injury and product
// + liability. However, the Licensor shall be entitled to the defense of contributory negligence.
// + The customer will take adequate precautions in the case, that the software is not working properly. The customer will test
// + the software for his purpose before any operational usage. The customer will backup his data before using the software.
// + The customer understands that the Licensor collects, stores and processes, and, where required, forwards, customer data
// + to third parties to the extent necessary for executing the agreement, subject to applicable data protection and privacy regulations.
// + *) The territory aspect only refers to the place where the Software is used, not its programmed range.
// + #### END OF LICENSING TERMS ####
// + Note: For information on license extensions (e.g. commercial use), please contact us at info(@)hisystems.de.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 
#include "sbus.h"
#include "main.h"
 
// #if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
 
unsigned char NewSBusData = 0, sBusBuffer[25];
 
//############################################################################
// USART1 initialisation from killagreg
void SbusUartInit(void)
//############################################################################
{
// -- Start of USART1 initialisation for Spekturm seriell-mode
// USART1 Control and Status Register A, B, C and baud rate register
uint8_t sreg = SREG;
uint16_t ubrr = (uint16_t) ((uint32_t) SYSCLK/(8 * 100000) - 1);
// disable all interrupts before reconfiguration
cli();
// disable RX-Interrupt
UCSR1B &= ~(1 << RXCIE1);
// disable TX-Interrupt
UCSR1B &= ~(1 << TXCIE1);
// disable DRE-Interrupt
UCSR1B &= ~(1 << UDRIE1);
// set direction of RXD1 and TXD1 pins
// set RXD1 (PD2) as an input pin
PORTD |= (1 << PORTD2);
DDRD &= ~(1 << DDD2);
 
// set TXD1 (PD3) as an output pin
PORTD |= (1 << PORTD3);
DDRD |= (1 << DDD3);
// USART0 Baud Rate Register
// set clock divider
UBRR1H = (uint8_t)(ubrr>>8);
UBRR1L = (uint8_t)ubrr;
// enable double speed operation
UCSR1A |= (1 << U2X1);
// enable receiver and transmitter
//UCSR1B = (1<<RXEN1)|(1<<TXEN1);
 
UCSR1B = (1<<RXEN1);
// set asynchronous mode
UCSR1C &= ~(1 << UMSEL11);
UCSR1C &= ~(1 << UMSEL10);
// parity
UCSR1C <= (1 << UPM11); // even
UCSR1C &= ~(1 << UPM10);
// stop bit
UCSR1C |= (1 << USBS1); // two
// 8-bit
UCSR1B &= ~(1 << UCSZ12);
UCSR1C |= (1 << UCSZ11);
UCSR1C |= (1 << UCSZ10);
// flush receive buffer explicit
while(UCSR1A & (1<<RXC1)) UDR1;
// enable RX-interrupts at the end
UCSR1B |= (1 << RXCIE1);
// -- End of USART1 initialisation
// restore global interrupt flags
sBusBuffer[23] |= 4; // This Bit contains the 'Signal loss'
SREG = sreg;
return;
}
 
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#define MIN_FRAMEGAP 68 // 7ms
#define MAX_BYTEGAP 3 // 310us
 
//############################################################################
// Is called by the uart RX interrupt
//############################################################################
void SbusParser(unsigned char udr)
{
static unsigned char ptr = 0;
if(!SpektrumTimer && udr == 0x0f) // wait for the start
{
ptr = 0;
SpektrumTimer = 80; // 8ms gap
}
else
{
if(++ptr == 24) // last byte
{
NewSBusData = 1;
}
else
if(ptr > 24) ptr = 25;
else
{
sBusBuffer[ptr] = udr; // collect all bytes
}
}
}
 
void ProcessSBus(void)
{
static unsigned char load = 0;
unsigned char bitmask8 = 1, sbyte = 2, i, index = 1, process;
unsigned int bitmask11 = 256;
signed int signal = 0,tmp;
if(!(sBusBuffer[23] & 4)) // This Bit contains the 'Signal loss'
{
TIMSK1 &= ~_BV(ICIE1); // disable PPM-Input
if(EE_Parameter.FailsafeChannel == 0 || PPM_in[EE_Parameter.FailsafeChannel] < 100) // forces Failsafe if the receiver doesn't have 'signal loss' on Failsafe
{
if(SenderOkay < 200) SenderOkay += 20; else SenderOkay = 200;
}
signal = sBusBuffer[1];
if(!load--) { process = (12*11 - 8); load = 2;} else process = (4*11 - 8); // lowers the processor load
for(i = 0; i < process; i++) // collect the single bits
{
if(sBusBuffer[sbyte] & bitmask8) signal |= bitmask11;
bitmask8 *= 2;
if(!bitmask8)
{
bitmask8 = 1;
sbyte++;
}
bitmask11 *= 2;
if(bitmask11 == 2048)
{
bitmask11 = 1;
signal = (signal-1024) / 5; // the resolution is higher than required
tmp = (3 * (PPM_in[index]) + signal) / 4;
if(tmp > signal+1) tmp--; else
if(tmp < signal-1) tmp++;
if(SenderOkay >= 195) PPM_diff[index] = ((tmp - PPM_in[index]) / 3) * 3;
else PPM_diff[index] = 0;
PPM_in[index] = tmp;
signal = 0;
index++; // next channel
}
}
NewPpmData = 0; // Null bedeutet: Neue Daten
}
NewSBusData = 0;
}
 
//#endif
/branches/V0.88n S.BUS ATmega644 tempolo/sbus.h
0,0 → 1,13
#ifndef _SBUS_H
#define _SBUS_H
 
//#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
 
extern unsigned char NewSBusData, sBusBuffer[25];
extern void SbusParser(unsigned char);
extern void SbusUartInit(void);
extern void ProcessSBus(void);
 
//#endif
 
#endif
/branches/V0.88n S.BUS ATmega644 tempolo/user_receiver.c
0,0 → 1,24
//############################################################################
// Implement your own RC-decoding routines here
//############################################################################
 
#include "sbus.h"
 
//############################################################################
// Initialize the UART here
//############################################################################
void User_Receiver_Init(void)
{
SbusUartInit();
};
 
 
//############################################################################
// Is called by the uart RX interrupt
// UDR contains the received byte
//############################################################################
void User_RX_Parser(unsigned char udr)
{
SbusParser(udr);
};