Subversion Repositories FlightCtrl

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
2751 - 1
/*#######################################################################################
2
Flight Control
3
#######################################################################################*/
4
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
5
// + www.MikroKopter.com
6
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7
// + Software Nutzungsbedingungen (english version: see below)
8
// + der Fa. HiSystems GmbH, Flachsmeerstrasse 2, 26802 Moormerland - nachfolgend Lizenzgeber genannt -
9
// + Der Lizenzgeber räumt dem Kunden ein nicht-ausschließliches, zeitlich und räumlich* unbeschränktes Recht ein, die im den
10
// + Mikrocontroller verwendete Firmware für die Hardware Flight-Ctrl, Navi-Ctrl, BL-Ctrl, MK3Mag & PC-Programm MikroKopter-Tool 
11
// + - nachfolgend Software genannt - nur für private Zwecke zu nutzen.
12
// + Der Einsatz dieser Software ist nur auf oder mit Produkten des Lizenzgebers zulässig.
13
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
14
// + Die vom Lizenzgeber gelieferte Software ist urheberrechtlich geschützt. Alle Rechte an der Software sowie an sonstigen im
15
// + Rahmen der Vertragsanbahnung und Vertragsdurchführung überlassenen Unterlagen stehen im Verhältnis der Vertragspartner ausschließlich dem Lizenzgeber zu.
16
// + Die in der Software enthaltenen Copyright-Vermerke, Markenzeichen, andere Rechtsvorbehalte, Seriennummern sowie
17
// + sonstige der Programmidentifikation dienenden Merkmale dürfen vom Kunden nicht verändert oder unkenntlich gemacht werden.
18
// + Der Kunde trifft angemessene Vorkehrungen für den sicheren Einsatz der Software. Er wird die Software gründlich auf deren
19
// + Verwendbarkeit zu dem von ihm beabsichtigten Zweck testen, bevor er diese operativ einsetzt.
20
// + Die Haftung des Lizenzgebers wird - soweit gesetzlich zulässig - begrenzt in Höhe des typischen und vorhersehbaren
21
// + Schadens. Die gesetzliche Haftung bei Personenschäden und nach dem Produkthaftungsgesetz bleibt unberührt. Dem Lizenzgeber steht jedoch der Einwand 
22
// + des Mitverschuldens offen.
23
// + Der Kunde trifft angemessene Vorkehrungen für den Fall, dass die Software ganz oder teilweise nicht ordnungsgemäß arbeitet.
24
// + Er wird die Software gründlich auf deren Verwendbarkeit zu dem von ihm beabsichtigten Zweck testen, bevor er diese operativ einsetzt.
25
// + Der Kunde wird er seine Daten vor Einsatz der Software nach dem Stand der Technik sichern.
26
// + Der Kunde ist darüber unterrichtet, dass der Lizenzgeber seine Daten im zur Vertragsdurchführung erforderlichen Umfang
27
// + und auf Grundlage der Datenschutzvorschriften erhebt, speichert, verarbeitet und, sofern notwendig, an Dritte übermittelt.
28
// + *) Die räumliche Nutzung bezieht sich nur auf den Einsatzort, nicht auf die Reichweite der programmierten Software.
29
// + #### ENDE DER NUTZUNGSBEDINGUNGEN ####'
30
// +  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.
31
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
32
// + Software LICENSING TERMS
33
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
34
// + of HiSystems GmbH, Flachsmeerstrasse 2, 26802 Moormerland, Germany - the Licensor -
35
// + 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 
36
// + (the Software) exclusively for private purposes. The License is unrestricted with respect to time and territory*.
37
// + The Software may only be used with the Licensor's products.
38
// + The Software provided by the Licensor is protected by copyright. With respect to the relationship between the parties to this
39
// + agreement, all rights pertaining to the Software and other documents provided during the preparation and execution of this
40
// + agreement shall be the property of the Licensor.
41
// + The information contained in the Software copyright notices, trademarks, other legal reservations, serial numbers and other
42
// + features that can be used to identify the program may not be altered or defaced by the customer.
43
// + The customer shall be responsible for taking reasonable precautions
44
// + for the safe use of the Software. The customer shall test the Software thoroughly regarding its suitability for the
45
// + intended purpose before implementing it for actual operation. The Licensor's liability shall be limited to the extent of typical and
46
// + foreseeable damage to the extent permitted by law, notwithstanding statutory liability for bodily injury and product
47
// + liability. However, the Licensor shall be entitled to the defense of contributory negligence.
48
// + The customer will take adequate precautions in the case, that the software is not working properly. The customer will test
49
// + the software for his purpose before any operational usage. The customer will backup his data before using the software.
50
// + The customer understands that the Licensor collects, stores and processes, and, where required, forwards, customer data
51
// + to third parties to the extent necessary for executing the agreement, subject to applicable data protection and privacy regulations.
52
// + *) The territory aspect only refers to the place where the Software is used, not its programmed range.
53
// + #### END OF LICENSING TERMS ####
54
// + Note: For information on license extensions (e.g. commercial use), please contact us at info(@)hisystems.de.
55
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
56
 
57
#include "main.h"
58
#include "mymath.h"
59
#include "isqrt.h"
60
 
61
unsigned char h,m,s;
62
unsigned int BaroExpandActive = 0;
63
int MesswertNick,MesswertRoll,MesswertGier,RohMesswertNick,RohMesswertRoll;
64
int TrimNick, TrimRoll;
65
int AdNeutralNick = 0,AdNeutralRoll = 0,AdNeutralGier = 0,StartNeutralRoll = 0,StartNeutralNick = 0;
66
int BoatNeutralNick = 0,BoatNeutralRoll = 0,BoatNeutralGier = 0;
67
int Mittelwert_AccNick, Mittelwert_AccRoll;
68
unsigned int NeutralAccX=0, NeutralAccY=0;
69
int NaviAccNick, NaviAccRoll,NaviCntAcc = 0;
70
int NeutralAccZ = 0;
71
signed char NeutralAccZfine = 0;
72
unsigned char ControlHeading = 0;// in 2°
73
long IntegralNick = 0;
74
long IntegralRoll = 0;
75
long Integral_Gier = 0;
76
long Mess_IntegralNick = 0;
77
long Mess_IntegralRoll = 0;
78
long Mess_Integral_Gier = 0,Mess_Integral_Gier2 = 0;
79
long MittelIntegralNick,MittelIntegralRoll;
80
long SummeNick=0,SummeRoll=0;
81
volatile long Mess_Integral_Hoch = 0;
82
int  KompassValue = -1;
83
int  KompassSollWert = 0;
84
int  NC_CompassSetpoint = -1;
85
//int  KompassRichtung = 0;
86
char CalculateCompassTimer = 100;
87
unsigned char KompassFusion = 32;
88
unsigned int  KompassSignalSchlecht = 50;
89
unsigned char  MAX_GAS,MIN_GAS;
90
unsigned char HoehenReglerAktiv = 0;
91
unsigned char TrichterFlug = 0;
92
long Umschlag180Nick = 250000L, Umschlag180Roll = 250000L;
93
long  ErsatzKompass;
94
int   ErsatzKompassInGrad, CompassCorrected; // Kompasswert in Grad
95
int   GierGyroFehler = 0;
96
char GyroFaktor,GyroFaktorGier;
97
char IntegralFaktor,IntegralFaktorGier;
98
int  DiffNick,DiffRoll;
99
unsigned int StickGasHover = 127;
100
int HoverGasMin = 0, HoverGasMax = 1023;
101
int StickNick = 0,StickRoll = 0,StickGier = 0,StickGas = 0;
102
//int  Poti1 = 0, Poti2 = 0, Poti3 = 0, Poti4 = 0, Poti5 = 0, Poti6 = 0, Poti7 = 0, Poti8 = 0;
103
unsigned char Poti[9] = {0,0,0,0,0,0,0,0};
104
volatile unsigned char SenderOkay = 0;
105
char MotorenEin = 0,StartTrigger = 0;
106
long HoehenWert = 0;
107
long SollHoehe = 0;
108
signed int AltitudeSetpointTrimming = 0;
109
long FromNC_AltitudeSetpoint = 0;
110
unsigned char FromNC_AltitudeSpeed = 0;
111
unsigned char carefree_old = 50; // to make the Beep when switching
112
signed char WaypointTrimming = 0;
113
int CompassGierSetpoint = 0;
114
unsigned char CalibrationDone = 0;
115
char NeueKompassRichtungMerken = 0;
116
int LageKorrekturRoll = 0,LageKorrekturNick = 0, HoverGas = 0;
117
//float Ki =  FAKTOR_I;
118
int Ki = 10300 / 33;
119
unsigned char Looping_Nick = 0,Looping_Roll = 0;
120
unsigned char Looping_Links = 0, Looping_Rechts = 0, Looping_Unten = 0, Looping_Oben = 0;
121
 
122
unsigned char Parameter_Luftdruck_D  = 48;      // Wert : 0-250
123
unsigned char Parameter_HoehenSchalter = 0;      // Wert : 0-250
124
unsigned char Parameter_Hoehe_P      = 16;      // Wert : 0-32
125
unsigned char Parameter_Hoehe_ACC_Wirkung = 58; // Wert : 0-250
126
unsigned char Parameter_KompassWirkung = 64;    // Wert : 0-250
127
unsigned char Parameter_Hoehe_TiltCompensation = 100;        // Wert : 0-250
128
unsigned char Parameter_Gyro_D = 8;             // Wert : 0-250
129
unsigned char Parameter_Gyro_P = 150;           // Wert : 10-250
130
unsigned char Parameter_Gyro_I = 150;           // Wert : 0-250
131
unsigned char Parameter_Gyro_Gier_P = 150;      // Wert : 10-250
132
unsigned char Parameter_Gyro_Gier_I = 150;      // Wert : 10-250
133
unsigned char Parameter_Gier_P = 2;             // Wert : 1-20
134
unsigned char Parameter_I_Faktor = 10;          // Wert : 1-20
135
unsigned char Parameter_UserParam1 = 0;
136
unsigned char Parameter_UserParam2 = 0;
137
unsigned char Parameter_UserParam3 = 0;
138
unsigned char Parameter_UserParam4 = 0;
139
unsigned char Parameter_UserParam5 = 0;
140
unsigned char Parameter_UserParam6 = 0;
141
unsigned char Parameter_UserParam7 = 0;
142
unsigned char Parameter_UserParam8 = 0;
143
unsigned char Parameter_NickControl = 100;
144
unsigned char Parameter_ServoNickControl = 100;
145
unsigned char Parameter_ServoRollControl = 100;
146
unsigned char Parameter_ServoNickComp = 50;
147
unsigned char Parameter_ServoRollComp = 85;
148
unsigned char Parameter_LoopGasLimit = 70;
149
unsigned char Parameter_AchsKopplung1 = 90;
150
unsigned char Parameter_AchsKopplung2 = 65;
151
unsigned char Parameter_CouplingYawCorrection = 64;
152
//unsigned char Parameter_AchsGegenKopplung1 = 0;
153
unsigned char Parameter_DynamicStability = 100;
154
unsigned char Parameter_J16Bitmask;             // for the J16 Output
155
unsigned char Parameter_J16Timing;              // for the J16 Output
156
unsigned char Parameter_J17Bitmask;             // for the J17 Output
157
unsigned char Parameter_J17Timing;              // for the J17 Output
158
unsigned char Parameter_NaviGpsGain;
159
unsigned char Parameter_NaviGpsP;
160
unsigned char Parameter_NaviGpsI;
161
unsigned char Parameter_NaviGpsD;
162
unsigned char Parameter_NaviGpsA;
163
//unsigned char Parameter_NaviOperatingRadius;
164
unsigned char Parameter_NaviWindCorrection;
165
unsigned char Parameter_NaviSpeedCompensation;
166
unsigned char Parameter_ExternalControl;
167
unsigned char Parameter_GlobalConfig;
168
unsigned char Parameter_ExtraConfig;
169
unsigned char Parameter_MaximumAltitude;
170
unsigned char Parameter_Servo3,Parameter_Servo4,Parameter_Servo5;
171
unsigned char CareFree = 0;
172
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
173
 
174
int MaxStickNick = 0,MaxStickRoll = 0;
175
unsigned int  modell_fliegt = 0;
176
volatile unsigned char FC_StatusFlags = 0, FC_StatusFlags2 = 0;
177
unsigned char FC_StatusFlags3 = 0;
178
long GIER_GRAD_FAKTOR = 1291;
179
signed int KopplungsteilNickRoll,KopplungsteilRollNick;
180
signed int tmp_motorwert[MAX_MOTORS];
181
char VarioCharacter = ' ';
182
unsigned int HooverGasEmergencyPercent = 0; // The gas value for Emergency landing
183
unsigned int GasIsZeroCnt = 0; // to detect that the gas-stick is down for a while
184
signed int Variance = 0;
185
signed int CosAttitude; // for projection of hoover gas
186
unsigned char ACC_AltitudeControl = 0;
187
unsigned char LowVoltageLandingActive = 0;
188
unsigned char LowVoltageHomeActive = 0;
189
signed int DriftNick = 0, DriftRoll = 0;
190
unsigned char ServoFailsafeActive = 0; // moves Servos into the FS-Position
191
 
192
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
193
#define OPA_OFFSET_STEP 5
194
#else
195
#define OPA_OFFSET_STEP 10
196
#endif
197
 
198
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
199
//  Debugwerte zuordnen
200
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
201
void CopyDebugValues(void)
202
{
203
    DebugOut.Analog[0] = ToNaviCtrl.IntegralNick;//IntegralNick / (EE_Parameter.GyroAccFaktor * 4);
204
    DebugOut.Analog[1] = ToNaviCtrl.IntegralRoll;//IntegralRoll / (EE_Parameter.GyroAccFaktor * 4);
205
    DebugOut.Analog[2] = Mittelwert_AccNick / 4;
206
    DebugOut.Analog[3] = Mittelwert_AccRoll / 4;
207
    DebugOut.Analog[4] = (signed int) AdNeutralGier - AdWertGier;
208
        DebugOut.Analog[5] = HoehenWert/10;
209
    DebugOut.Analog[6] = Aktuell_az;//AdWertAccHoch;//(Mess_Integral_Hoch / 512);
210
    DebugOut.Analog[8] = KompassValue;
211
    DebugOut.Analog[9] = UBat;
212
    DebugOut.Analog[10] = SenderOkay;
213
    DebugOut.Analog[11] = ErsatzKompassInGrad;
214
    DebugOut.Analog[12] = Motor[0].SetPoint;
215
    DebugOut.Analog[13] = Motor[1].SetPoint;
216
    DebugOut.Analog[14] = Motor[2].SetPoint;
217
    DebugOut.Analog[15] = Motor[3].SetPoint;
218
    DebugOut.Analog[20] = ServoNickValue;
219
        DebugOut.Analog[21] = HoverGas;
220
    DebugOut.Analog[22] = Capacity.ActualCurrent;
221
    DebugOut.Analog[23] = Capacity.UsedCapacity;
222
        DebugOut.Analog[24] = SollHoehe/10;    
223
//    DebugOut.Analog[27] = KompassSollWert;
224
        DebugOut.Analog[29] = Capacity.MinOfMaxPWM;
225
    DebugOut.Analog[30] = GPS_Nick;
226
    DebugOut.Analog[31] = GPS_Roll;
227
    if(VersionInfo.HardwareError[0] || VersionInfo.HardwareError[1]) DebugOut.Status[1] |= 1; else DebugOut.Status[1] &= 0xfe;
228
//DebugOut.Analog[16] = MinBlTemperture; 
229
//DebugOut.Analog[17] = MaxBlTemperture; 
230
//DebugOut.Analog[16] = Variance;
231
//DebugOut.Analog[17] = VarioMeter;
232
//DebugOut.Analog[16] = GasIsZeroCnt;
233
//DebugOut.Analog[18] = HoehenWertF;            
234
//DebugOut.Analog[25] = Parameter_Hoehe_P;
235
//DebugOut.Analog[26] = Parameter_Luftdruck_D;
236
}
237
 
238
 
239
void Piep(unsigned char Anzahl, unsigned int dauer)
240
{
241
 unsigned int wait = 0;
242
 if(MotorenEin) return; //auf keinen Fall im Flug!
243
GRN_OFF;
244
 while(Anzahl--)
245
 {
246
  beeptime = dauer;
247
  wait = dauer;
248
  while(beeptime || wait)
249
   {
250
    if(UpdateMotor)
251
         {
252
          UpdateMotor = 0;
253
          if(!beeptime) wait--;
254
          LIBFC_Polling();
255
         };
256
   }
257
 }
258
GRN_ON;
259
}
260
 
261
//############################################################################
262
// Messwerte beim Ermitteln der Nullage
263
void CalibrierMittelwert(void)
264
//############################################################################
265
{
266
//    if(PlatinenVersion == 13) SucheGyroOffset();
267
    // ADC auschalten, damit die Werte sich nicht während der Berechnung ändern
268
        ANALOG_OFF;
269
        MesswertNick = AdWertNick;
270
        MesswertRoll = AdWertRoll;
271
        MesswertGier = AdWertGier;
272
        Mittelwert_AccNick = ACC_AMPLIFY * AdWertAccNick;
273
        Mittelwert_AccRoll = ACC_AMPLIFY * AdWertAccRoll;
274
   // ADC einschalten
275
    ANALOG_ON;
276
        Umschlag180Nick = (long) EE_Parameter.WinkelUmschlagNick * 2500L;
277
        Umschlag180Roll = (long) EE_Parameter.WinkelUmschlagRoll * 2500L;
278
}
279
 
280
void StoreNeutralToEeprom(void)
281
{
282
        BoatNeutralNick = AdNeutralNick;
283
        BoatNeutralRoll = AdNeutralRoll;
284
        BoatNeutralGier = AdNeutralGier;
285
        SetParamWord(PID_ACC_NICK, (uint16_t)NeutralAccX);
286
        SetParamWord(PID_ACC_ROLL, (uint16_t)NeutralAccY);
287
        SetParamWord(PID_GYRO_NICK,(uint16_t)BoatNeutralNick);
288
        SetParamWord(PID_GYRO_ROLL,(uint16_t)BoatNeutralRoll);
289
        SetParamWord(PID_GYRO_YAW,(uint16_t)BoatNeutralGier);
290
}
291
 
292
//############################################################################
293
//  Nullwerte ermitteln
294
//  Parameter: 0 -> after switch on (ignore ACC-Z fault)
295
//  Parameter: 1 -> before Start
296
//  Parameter: 2 -> calibrate and store ACC
297
//  Parameter: 3 -> use stored Gyro calibration Data from EEPROM (Boat-Mode)
298
unsigned char SetNeutral(unsigned char AdjustmentMode)  // retuns: "sucess"
299
//############################################################################
300
{
301
        unsigned char i, sucess = 1;
302
        unsigned int gier_neutral = 0, nick_neutral = 0, roll_neutral = 0, acc_z_neutral = 0, barotest;
303
    VersionInfo.HardwareError[0] = 0;
304
//    HEF4017Reset_ON;
305
        NeutralAccX = 0;
306
        NeutralAccY = 0;
307
        NeutralAccZ = 0;
308
        NeutralAccZfine = 0;
309
 
310
    AdNeutralNick = 0;
311
        AdNeutralRoll = 0;
312
        AdNeutralGier = 0;
313
 
314
    Parameter_AchsKopplung1 = 0;
315
    Parameter_AchsKopplung2 = 0;
316
 
317
    ExpandBaro = 0;
318
    if(AdjustmentMode == 3)  FC_StatusFlags3 |= FC_STATUS3_BOAT;
319
        // else FC_StatusFlags3 &= ~FC_STATUS3_BOAT; -> do not clear that
320
 
321
    CalibrierMittelwert();
322
    Delay_ms_Mess(100);
323
        CalibrierMittelwert();
324
 
325
    if((EE_Parameter.GlobalConfig & CFG_HOEHENREGELUNG))  // Höhenregelung aktiviert?
326
     {
327
      if((MessLuftdruck > 950) || (MessLuftdruck < 750) || ExpandBaro) SucheLuftruckOffset();
328
     }
329
 
330
        barotest = MessLuftdruck;
331
#define NEUTRAL_FILTER 32
332
        OCR0A += OPA_OFFSET_STEP;
333
        OCR0B = 255 - OCR0A;
334
    for(i=0; i<NEUTRAL_FILTER; i++)
335
         {
336
          Delay_ms_Mess(10);
337
          gier_neutral += AdWertGier;
338
          nick_neutral += AdWertNick;
339
          roll_neutral += AdWertRoll;
340
          acc_z_neutral += Aktuell_az;
341
         }
342
        if(MessLuftdruck < 1010 && MessLuftdruck > 20) BaroStep = barotest - MessLuftdruck;
343
        OCR0A -= OPA_OFFSET_STEP;
344
        OCR0B = 255 - OCR0A;
345
     AdNeutralNick = (nick_neutral+NEUTRAL_FILTER/2) / (NEUTRAL_FILTER / 8);
346
         AdNeutralRoll = (roll_neutral+NEUTRAL_FILTER/2) / (NEUTRAL_FILTER / 8);
347
         AdNeutralGier = (gier_neutral+NEUTRAL_FILTER/2) / (NEUTRAL_FILTER);
348
     NeutralAccZ = (acc_z_neutral+NEUTRAL_FILTER/2) / (NEUTRAL_FILTER);
349
 
350
     StartNeutralRoll = AdNeutralRoll;
351
     StartNeutralNick = AdNeutralNick;
352
 
353
     if(AdjustmentMode == 2)
354
     {
355
            NeutralAccX = abs(Mittelwert_AccNick) / (2*ACC_AMPLIFY);
356
            NeutralAccY = abs(Mittelwert_AccRoll) / (2*ACC_AMPLIFY);
357
                // Save ACC neutral settings to eeprom
358
                StoreNeutralToEeprom();
359
    }
360
    else
361
    {
362
                // restore from eeprom
363
                NeutralAccX = (int16_t)GetParamWord(PID_ACC_NICK);
364
                NeutralAccY = (int16_t)GetParamWord(PID_ACC_ROLL);
365
                // strange settings?
366
                if(((unsigned int) NeutralAccX > 2048) || ((unsigned int) NeutralAccY > 2048)/* || ((unsigned int) NeutralAccZ > 1024)*/)
367
                {
368
                        printf("\n\rACC not calibrated!\r\n");
369
                        NeutralAccX = abs(Mittelwert_AccNick) / (2*ACC_AMPLIFY);
370
                        NeutralAccY = abs(Mittelwert_AccRoll) / (2*ACC_AMPLIFY);
371
                        sucess = 0;
372
                }
373
 
374
        // restore from eeprom
375
        BoatNeutralNick = (int16_t)GetParamWord(PID_GYRO_NICK);
376
        BoatNeutralRoll = (int16_t)GetParamWord(PID_GYRO_ROLL);
377
        BoatNeutralGier = (int16_t)GetParamWord(PID_GYRO_YAW);
378
 
379
     if(FC_StatusFlags3 & FC_STATUS3_BOAT) // Read Gyro Data from eeprom
380
     {
381
                // strange settings?
382
                if(((unsigned int) BoatNeutralNick > (600 * 16)) || ((unsigned int) BoatNeutralNick < (400 * 16))
383
                   || ((unsigned int) BoatNeutralRoll > (600 * 16)) || ((unsigned int) BoatNeutralRoll < (400 * 16))
384
                   || ((unsigned int) BoatNeutralGier > (600 * 2)) || ((unsigned int) BoatNeutralGier < (400 * 2)))
385
                {
386
                        printf("\n\rGyro calibration data not valid\r\n");
387
                        sucess = 0;
388
                        FC_StatusFlags3 &= ~FC_STATUS3_BOAT;
389
                }
390
                else
391
                {
392
                        AdNeutralNick = BoatNeutralNick;
393
                        AdNeutralRoll = BoatNeutralRoll;
394
                        AdNeutralGier = BoatNeutralGier;
395
                }
396
     }
397
    }
398
        EEAR = EE_DUMMY;  // Set the EEPROM Address pointer to an unused space
399
        MesswertNick = 0;
400
    MesswertRoll = 0;
401
    MesswertGier = 0;
402
    Delay_ms_Mess(200);
403
    Mittelwert_AccNick = ACC_AMPLIFY * AdWertAccNick;
404
    Mittelwert_AccRoll = ACC_AMPLIFY * AdWertAccRoll;
405
    IntegralNick = EE_Parameter.GyroAccFaktor * (long)Mittelwert_AccNick;
406
    IntegralRoll = EE_Parameter.GyroAccFaktor * (long)Mittelwert_AccRoll;
407
    Mess_IntegralNick = IntegralNick;
408
    Mess_IntegralRoll = IntegralRoll;
409
    Mess_Integral_Gier = 0;
410
    KompassSollWert = KompassValue;
411
        NC_CompassSetpoint = -1;
412
        KompassSignalSchlecht = 100;
413
        Umschlag180Nick = ((long) EE_Parameter.WinkelUmschlagNick * 2500L) + 15000L;
414
        Umschlag180Roll = ((long) EE_Parameter.WinkelUmschlagRoll * 2500L) + 15000L;
415
    ErsatzKompass = KompassValue * GIER_GRAD_FAKTOR;
416
    GierGyroFehler = 0;
417
    LED_Init();
418
    if(AdjustmentMode != 0) FC_StatusFlags |= FC_STATUS_CALIBRATE;
419
    FromNaviCtrl_Value.Kalman_K = -1;
420
    FromNaviCtrl_Value.Kalman_MaxDrift = 0;
421
    FromNaviCtrl_Value.Kalman_MaxFusion = 32;
422
    SenderOkay = 100;
423
 
424
    if(ServoActive)     DDRD  |=0x80; // enable J7 -> Servo signal
425
        else
426
         {
427
      if((EE_Parameter.ServoCompInvert & SERVO_NICK_INV) && (EE_Parameter.ServoCompInvert & SERVO_RELATIVE)) NickServoValue = 12000;//((128 + 60) * 4 * 16); // neutral position = upper 1/4//    else    
428
          else NickServoValue = ((128 - 60) * 4 * 16); // neutral position = lower 1/4
429
          CalculateServoSignals = 1;
430
          CalculateServo(); // nick
431
          CalculateServo(); // roll
432
         }
433
 
434
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
435
    signed int tilt1, tilt2;
436
                tilt1 = (int)(IntegralNick/GIER_GRAD_FAKTOR);  // nick angle in deg
437
                tilt2 = (int)(IntegralRoll/GIER_GRAD_FAKTOR);  // roll angle in deg
438
                tilt1 = (int16_t)ihypot(tilt1,tilt2);                   // tilt angle over all 
439
                CosAttitude = c_cos_8192(tilt1);                               
440
                NeutralAccZ = (long)((long) (NeutralAccZ - 512) * 8192 + 4096) / CosAttitude + 512;
441
                if(tilt1 > 20) sucess = 0; // calibration must be within 20° Tilt angle 
442
                if(AdjustmentMode != 0 && ACC_AltitudeControl) if((NeutralAccZ < 682 - 30) || (NeutralAccZ > 682 + 35)) { VersionInfo.HardwareError[0] |= FC_ERROR0_ACC_TOP; sucess = 0;};
443
#else
444
        NeutralAccZ = (int16_t)GetParamWord(PID_ACC_TOP);
445
        EEAR = EE_DUMMY;  // Set the EEPROM Address pointer to an unused space
446
#endif
447
        if((AdNeutralNick < 150 * 16) || (AdNeutralNick > 850 * 16)) { VersionInfo.HardwareError[0] |= FC_ERROR0_GYRO_NICK; };
448
        if((AdNeutralRoll < 150 * 16) || (AdNeutralRoll > 850 * 16)) { VersionInfo.HardwareError[0] |= FC_ERROR0_GYRO_ROLL; };
449
        if((AdNeutralGier < 150 * 2)  || (AdNeutralGier > 850 * 2))  { VersionInfo.HardwareError[0] |= FC_ERROR0_GYRO_YAW; };
450
        if((NeutralAccX < 300) || (NeutralAccX > 750)) { VersionInfo.HardwareError[0] |= FC_ERROR0_ACC_NICK; };
451
        if((NeutralAccY < 300) || (NeutralAccY > 750)) { VersionInfo.HardwareError[0] |= FC_ERROR0_ACC_ROLL; };
452
        if((NeutralAccZ < 512) || (NeutralAccZ > 850)) { VersionInfo.HardwareError[0] |= FC_ERROR0_ACC_TOP; };
453
    if(VersionInfo.HardwareError[0]) sucess = 0;
454
    carefree_old = 70;
455
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
456
        LIBFC_HoTT_Clear();
457
        ACC_AltitudeFusion(2); // initalisation
458
#endif
459
    StartLuftdruck = Luftdruck;
460
    VarioMeter = 0;
461
        SummenHoehe = 0;    Mess_Integral_Hoch = 0;
462
        DebugOut.Analog[28] = 0; // I2C-Counter
463
        CalcExpandBaroStep();
464
        if(FC_StatusFlags3 & FC_STATUS3_BOAT && !EE_Parameter.Driftkomp) EE_Parameter.Driftkomp = 4;
465
        ShutterCounter = 0;
466
/*
467
//+++++++++++++++++++++++++++++++++++++++++++
468
//For testing the expandBaro at 30m                            
469
                                ExpandBaro -= 1;
470
                                OCR0A = DruckOffsetSetting - OPA_OFFSET_STEP * ExpandBaro; // increase offset to shift ADC down
471
                                OCR0B = 255 - OCR0A;
472
                                CalcExpandBaroStep();
473
//+++++++++++++++++++++++++++++++++++++++++++
474
*/
475
 return(sucess);
476
}
477
 
478
 
479
//############################################################################
480
// Bearbeitet die Messwerte
481
void Mittelwert(void)
482
//############################################################################
483
{
484
    static signed long tmpl,tmpl2,tmpl3,tmpl4;
485
        static signed int oldNick, oldRoll, d2Roll, d2Nick;
486
        signed long winkel_nick, winkel_roll;
487
        MesswertGier = (signed int) AdNeutralGier - AdWertGier;
488
    MesswertNick = (signed int) AdWertNickFilter / 8;
489
    MesswertRoll = (signed int) AdWertRollFilter / 8;
490
    RohMesswertNick = MesswertNick;
491
    RohMesswertRoll = MesswertRoll;
492
 
493
// Beschleunigungssensor  ++++++++++++++++++++++++++++++++++++++++++++++++
494
        Mittelwert_AccNick = (Mittelwert_AccNick * 3 + ((ACC_AMPLIFY * AdWertAccNick))) / 4L;
495
        Mittelwert_AccRoll = (Mittelwert_AccRoll * 3 + ((ACC_AMPLIFY * AdWertAccRoll))) / 4L;
496
    NaviAccNick    += AdWertAccNick;
497
    NaviAccRoll    += AdWertAccRoll;
498
    NaviCntAcc++;
499
 
500
//++++++++++++++++++++++++++++++++++++++++++++++++
501
        HoehenWert = HoehenWert_Mess;
502
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
503
        HoehenWertF = HoehenWertF_Mess;
504
#else
505
        HoehenWertF = HoehenWert;
506
#endif
507
//++++++++++++++++++++++++++++++++++++++++++++++++
508
// ADC einschalten
509
    ANALOG_ON;
510
        AdReady = 0;
511
//++++++++++++++++++++++++++++++++++++++++++++++++
512
 
513
    if(Mess_IntegralRoll > 93000L) winkel_roll = 93000L;
514
        else if(Mess_IntegralRoll <-93000L) winkel_roll = -93000L;
515
        else winkel_roll = Mess_IntegralRoll;
516
 
517
    if(Mess_IntegralNick > 93000L) winkel_nick = 93000L;
518
        else if(Mess_IntegralNick <-93000L) winkel_nick = -93000L;
519
        else winkel_nick = Mess_IntegralNick;
520
 
521
// Gier  ++++++++++++++++++++++++++++++++++++++++++++++++
522
   Mess_Integral_Gier += MesswertGier;
523
   ErsatzKompass += MesswertGier;
524
// Kopplungsanteil  +++++++++++++++++++++++++++++++++++++
525
      if(!Looping_Nick && !Looping_Roll && (Parameter_GlobalConfig & CFG_ACHSENKOPPLUNG_AKTIV))
526
         {
527
            tmpl3 = (MesswertRoll * winkel_nick) / 2048L;
528
            tmpl3 *= Parameter_AchsKopplung2; //65
529
            tmpl3 /= 4096L;
530
            tmpl4 = (MesswertNick * winkel_roll) / 2048L;
531
            tmpl4 *= Parameter_AchsKopplung2; //65
532
            tmpl4 /= 4096L;
533
            KopplungsteilNickRoll = tmpl3;
534
            KopplungsteilRollNick = tmpl4;
535
            tmpl4 -= tmpl3;
536
            ErsatzKompass += tmpl4;
537
            if(!Parameter_CouplingYawCorrection) Mess_Integral_Gier -= tmpl4/2; // Gier nachhelfen
538
 
539
            tmpl = ((MesswertGier + tmpl4) * winkel_nick) / 2048L;
540
            tmpl *= Parameter_AchsKopplung1;  // 90
541
            tmpl /= 4096L;
542
            tmpl2 = ((MesswertGier + tmpl4) * winkel_roll) / 2048L;
543
            tmpl2 *= Parameter_AchsKopplung1;
544
            tmpl2 /= 4096L;
545
            if(abs(MesswertGier) > 64) if(labs(tmpl) > 128 || labs(tmpl2) > 128) TrichterFlug = 1;
546
            //MesswertGier += (Parameter_CouplingYawCorrection * tmpl4) / 256;
547
         }
548
      else  tmpl = tmpl2 = KopplungsteilNickRoll = KopplungsteilRollNick = 0;
549
                        TrimRoll = tmpl - tmpl2 / 100L;
550
                        TrimNick = -tmpl2 + tmpl / 100L;
551
// Kompasswert begrenzen  ++++++++++++++++++++++++++++++++++++++++++++++++
552
                    if(ErsatzKompass >= (360L * GIER_GRAD_FAKTOR)) ErsatzKompass -= 360L * GIER_GRAD_FAKTOR;  // 360° Umschlag
553
                    if(ErsatzKompass < 0)                          ErsatzKompass += 360L * GIER_GRAD_FAKTOR;
554
// Roll  ++++++++++++++++++++++++++++++++++++++++++++++++
555
            Mess_IntegralRoll +=  MesswertRoll + TrimRoll - LageKorrekturRoll;
556
            if(Mess_IntegralRoll > Umschlag180Roll)
557
            {
558
             Mess_IntegralRoll  = -(Umschlag180Roll - 25000L);
559
            }
560
            if(Mess_IntegralRoll <-Umschlag180Roll)
561
            {
562
             Mess_IntegralRoll =  (Umschlag180Roll - 25000L);
563
            }
564
// Nick  ++++++++++++++++++++++++++++++++++++++++++++++++
565
            Mess_IntegralNick  += MesswertNick + TrimNick - LageKorrekturNick;
566
            if(Mess_IntegralNick > Umschlag180Nick)
567
             {
568
              Mess_IntegralNick = -(Umschlag180Nick - 25000L);
569
             }
570
            if(Mess_IntegralNick <-Umschlag180Nick)
571
            {
572
             Mess_IntegralNick =  (Umschlag180Nick - 25000L);
573
            }
574
 
575
    Integral_Gier  = Mess_Integral_Gier;
576
    IntegralNick = Mess_IntegralNick;
577
    IntegralRoll = Mess_IntegralRoll;
578
 
579
 
580
#define D_LIMIT 128
581
 
582
   MesswertNick = HiResNick / 8;
583
   MesswertRoll = HiResRoll / 8;
584
 
585
   if(AdWertNick < 15)   MesswertNick = -1000;  if(AdWertNick <  7)   MesswertNick = -2000;
586
//   if(PlatinenVersion == 10)  { if(AdWertNick > 1010) MesswertNick = +1000;  if(AdWertNick > 1017) MesswertNick = +2000; }
587
//   else  
588
   {  if(AdWertNick > 2000) MesswertNick = +1000;  if(AdWertNick > 2015) MesswertNick = +2000; }
589
   if(AdWertRoll < 15)   MesswertRoll = -1000;  if(AdWertRoll <  7)   MesswertRoll = -2000;
590
//   if(PlatinenVersion == 10) { if(AdWertRoll > 1010) MesswertRoll = +1000;  if(AdWertRoll > 1017) MesswertRoll = +2000; }
591
//   else 
592
   { if(AdWertRoll > 2000) MesswertRoll = +1000;  if(AdWertRoll > 2015) MesswertRoll = +2000;  }
593
 
594
  if(Parameter_Gyro_D)
595
  {
596
   d2Nick = HiResNick - oldNick;
597
   oldNick = (oldNick + HiResNick)/2;
598
   if(d2Nick > D_LIMIT) d2Nick = D_LIMIT;
599
   else if(d2Nick < -D_LIMIT) d2Nick = -D_LIMIT;
600
 
601
   d2Roll = HiResRoll - oldRoll;
602
   oldRoll = (oldRoll + HiResRoll)/2;
603
   if(d2Roll > D_LIMIT) d2Roll = D_LIMIT;
604
   else if(d2Roll < -D_LIMIT) d2Roll = -D_LIMIT;
605
 
606
   MesswertNick += (d2Nick * (signed int) Parameter_Gyro_D) / 16;
607
   MesswertRoll += (d2Roll * (signed int) Parameter_Gyro_D) / 16;
608
   HiResNick += (d2Nick * (signed int) Parameter_Gyro_D);
609
   HiResRoll += (d2Roll * (signed int) Parameter_Gyro_D);
610
  }
611
 
612
 if(RohMesswertRoll > 0) TrimRoll  += ((long) abs(KopplungsteilNickRoll) * Parameter_CouplingYawCorrection) / 64L;
613
 else                    TrimRoll -= ((long) abs(KopplungsteilNickRoll) * Parameter_CouplingYawCorrection) / 64L;
614
 if(RohMesswertNick > 0) TrimNick += ((long) abs(KopplungsteilRollNick) * Parameter_CouplingYawCorrection) / 64L;
615
 else                    TrimNick -= ((long) abs(KopplungsteilRollNick) * Parameter_CouplingYawCorrection) / 64L;
616
 
617
  if(Parameter_GlobalConfig & CFG_DREHRATEN_BEGRENZER && !Looping_Nick && !Looping_Roll)
618
  {
619
    if(RohMesswertNick > 256)       MesswertNick += 1 * (RohMesswertNick - 256);
620
    else if(RohMesswertNick < -256) MesswertNick += 1 * (RohMesswertNick + 256);
621
    if(RohMesswertRoll > 256)       MesswertRoll += 1 * (RohMesswertRoll - 256);
622
    else if(RohMesswertRoll < -256) MesswertRoll += 1 * (RohMesswertRoll + 256);
623
  }
624
}
625
 
626
//############################################################################
627
// Senden der Motorwerte per I2C-Bus
628
void SendMotorData(void)
629
//############################################################################
630
{
631
 unsigned char i;
632
    if(!MotorenEin)
633
        {
634
         FC_StatusFlags &= ~(FC_STATUS_MOTOR_RUN | FC_STATUS_FLY);
635
                 FC_StatusFlags2 &= ~FC_STATUS2_WAIT_FOR_TAKEOFF;
636
                 for(i=0;i<MAX_MOTORS;i++)
637
                  {
638
                   if(!PC_MotortestActive)  MotorTest[i] = 0;
639
                   Motor[i].SetPoint = MotorTest[i];
640
                   Motor[i].SetPointLowerBits = 0;
641
/*
642
 Motor[i].SetPoint = MotorTest[i] / 4;            // testing the high resolution
643
 Motor[i].SetPointLowerBits = MotorTest[i] % 4;
644
*/
645
                  }
646
          if(PC_MotortestActive) PC_MotortestActive--;
647
        }
648
        else FC_StatusFlags |= FC_STATUS_MOTOR_RUN;
649
 
650
// ++++++++++++++++++++++++++++++++++++++++++
651
 
652
// ++++++++++++++++++++++++++++++++++++++++++
653
#ifdef REDUNDANT_FC_SLAVE
654
        I2CTimeout = 100;
655
        return; // don't send I2C-Data
656
#endif
657
 
658
#ifdef REDUNDANT_FC_MASTER
659
if(Parameter_UserParam7 > 150)
660
 {
661
        FC_StatusFlags3 |= FC_STATUS3_REDUNDANCE_TEST;
662
        // Make noise
663
        if((BeepMuster == 0xffff)) { beeptime = 25000; BeepMuster = 0x0080; }
664
        // Do not send I2C-Data
665
        if((FC_StatusFlags3 & FC_STATUS3_REDUNDANCE_AKTIVE) || !(FC_StatusFlags |= FC_STATUS_MOTOR_RUN))
666
         {
667
          I2CTimeout = 100;
668
          return; // don't send I2C-Data
669
         }
670
 }
671
#endif
672
    if(I2C_TransferActive)
673
         {
674
          I2C_TransferActive = 0; // enable for the next time
675
         }
676
        else
677
    {
678
//     motor_write = 0;
679
     I2C_Start(TWI_STATE_MOTOR_TX); //Start I2C Interrupt Mode
680
        }
681
}
682
 
683
unsigned char GetChannelValue(unsigned char ch) // gives the unsigned value of the channel
684
{
685
 int tmp2;
686
 if(ch == 0) return(0);
687
 tmp2 = PPM_in[ch] + 127;
688
 if(tmp2 > 255) tmp2 = 255; else if(tmp2 < 0) tmp2 = 0;
689
 return(tmp2);   
690
}
691
 
692
//############################################################################
693
// Trägt ggf. das Poti als Parameter ein
694
void ParameterZuordnung(void)
695
//############################################################################
696
{
697
 unsigned char tmp,i;
698
  for(i=0;i<8;i++)
699
    {
700
     int tmp2;
701
         tmp = EE_Parameter.Kanalbelegung[K_POTI1 + i];
702
         tmp2 = PPM_in[tmp] + 127;
703
         if(tmp2 > 255) tmp2 = 255; else if(tmp2 < 0) tmp2 = 0;
704
 
705
         if(tmp == 25) Poti[i] = tmp2; // 25 = WaypointEvent channel -> no filter
706
         else
707
     if(tmp2 != Poti[i])
708
          {
709
           Poti[i] += (tmp2 - Poti[i]) / 4;
710
       if(Poti[i] > tmp2) Poti[i]--;
711
           else Poti[i]++;
712
          }
713
        }
714
 CHK_POTI_MM(Parameter_Luftdruck_D,EE_Parameter.Luftdruck_D,0,100);
715
 CHK_POTI_MM(Parameter_Hoehe_P,EE_Parameter.Hoehe_P,0,100);
716
 CHK_POTI_MM(Parameter_Gyro_P,EE_Parameter.Gyro_P,10,255);
717
 CHK_POTI_MM(Parameter_J16Timing,EE_Parameter.J16Timing,5,255);
718
 CHK_POTI_MM(Parameter_J17Timing,EE_Parameter.J17Timing,5,255);
719
 if(EE_Parameter.Servo3 == 247) { if(PORTC & (1<<PORTC2)) Parameter_Servo3 = EE_Parameter.Servo3OnValue; else Parameter_Servo3 = EE_Parameter.Servo3OffValue;}       // Out1 (J16)
720
 else if(EE_Parameter.Servo3 == 246) { if(PORTC & (1<<PORTC3)) Parameter_Servo3 = EE_Parameter.Servo3OnValue; else Parameter_Servo3 = EE_Parameter.Servo3OffValue;}
721
 else CHK_POTI_MM(Parameter_Servo3,EE_Parameter.Servo3, 24, 255);
722
 
723
 if(EE_Parameter.Servo4 == 247) { if(PORTC & (1<<PORTC2)) Parameter_Servo4 = EE_Parameter.Servo4OnValue; else Parameter_Servo4 = EE_Parameter.Servo4OffValue;}
724
 else if(EE_Parameter.Servo4 == 246) { if(PORTC & (1<<PORTC3)) Parameter_Servo4 = EE_Parameter.Servo4OnValue; else Parameter_Servo4 = EE_Parameter.Servo4OffValue;}  // Out2 (J17)
725
 else CHK_POTI_MM(Parameter_Servo4,EE_Parameter.Servo4, 24, 255);
726
 
727
 CHK_POTI_MM(Parameter_Servo5,EE_Parameter.Servo5, 24, 255);
728
 Parameter_HoehenSchalter = GetChannelValue(EE_Parameter.HoeheChannel);
729
 CHK_POTI(Parameter_Hoehe_ACC_Wirkung,EE_Parameter.Hoehe_ACC_Wirkung);
730
 CHK_POTI(Parameter_Hoehe_TiltCompensation,EE_Parameter.Hoehe_TiltCompensation);
731
 CHK_POTI(Parameter_KompassWirkung,EE_Parameter.KompassWirkung);
732
 CHK_POTI(Parameter_Gyro_I,EE_Parameter.Gyro_I);
733
 CHK_POTI(Parameter_Gyro_D,EE_Parameter.Gyro_D);
734
 CHK_POTI(Parameter_Gyro_Gier_P,EE_Parameter.Gyro_Gier_P);
735
 CHK_POTI(Parameter_Gyro_Gier_I,EE_Parameter.Gyro_Gier_I);
736
 CHK_POTI(Parameter_I_Faktor,EE_Parameter.I_Faktor);
737
 CHK_POTI(Parameter_UserParam1,EE_Parameter.UserParam1);
738
 CHK_POTI(Parameter_UserParam2,EE_Parameter.UserParam2);
739
 CHK_POTI(Parameter_UserParam3,EE_Parameter.UserParam3);
740
 CHK_POTI(Parameter_UserParam4,EE_Parameter.UserParam4);
741
 CHK_POTI(Parameter_UserParam5,EE_Parameter.UserParam5);
742
 CHK_POTI(Parameter_UserParam6,EE_Parameter.UserParam6);
743
 CHK_POTI(Parameter_UserParam7,EE_Parameter.UserParam7);
744
 CHK_POTI(Parameter_UserParam8,EE_Parameter.UserParam8);
745
 CHK_POTI(Parameter_ServoNickControl,EE_Parameter.ServoNickControl);
746
 CHK_POTI(Parameter_ServoRollControl,EE_Parameter.ServoRollControl);
747
 CHK_POTI(Parameter_ServoNickComp,EE_Parameter.ServoNickComp);
748
 CHK_POTI(Parameter_ServoRollComp,EE_Parameter.ServoRollComp);
749
 CHK_POTI(Parameter_LoopGasLimit,EE_Parameter.LoopGasLimit);
750
 CHK_POTI(Parameter_AchsKopplung1,EE_Parameter.AchsKopplung1);
751
 CHK_POTI(Parameter_AchsKopplung2,EE_Parameter.AchsKopplung2);
752
 CHK_POTI(Parameter_CouplingYawCorrection,EE_Parameter.CouplingYawCorrection);
753
 CHK_POTI(Parameter_MaximumAltitude,EE_Parameter.MaxAltitude);
754
// if((NC_To_FC_MaxAltitude && NC_To_FC_MaxAltitude < Parameter_MaximumAltitude) || Parameter_MaximumAltitude == 0) Parameter_MaximumAltitude = NC_To_FC_MaxAltitude;
755
 Parameter_GlobalConfig = EE_Parameter.GlobalConfig;
756
 Parameter_ExtraConfig = EE_Parameter.ExtraConfig;
757
// CHK_POTI(Parameter_AchsGegenKopplung1,EE_Parameter.AchsGegenKopplung1,0,255);
758
 CHK_POTI(Parameter_DynamicStability,EE_Parameter.DynamicStability);
759
 CHK_POTI(Parameter_ExternalControl,EE_Parameter.ExternalControl);
760
 Ki = 10300 / (Parameter_I_Faktor + 1);
761
 MAX_GAS = EE_Parameter.Gas_Max;
762
 MIN_GAS = EE_Parameter.Gas_Min;
763
 
764
 if(EE_Parameter.CareFreeChannel)
765
   {
766
        CareFree = 1;
767
        if(PPM_in[EE_Parameter.CareFreeChannel] < -64) CareFree = 0;
768
//    if(tmp >= 248 && Poti[255 - tmp] < 50) CareFree = 0; 
769
    if(carefree_old != CareFree)
770
    {
771
      if(carefree_old < 3)
772
           {
773
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
774
                if(CareFree) { beeptime = 1500;  if(!SpeakHoTT) SpeakHoTT = SPEAK_CF_ON; }
775
            else { beeptime = 200;  if(!SpeakHoTT) SpeakHoTT = SPEAK_CF_OFF; }
776
#else
777
                if(CareFree) beeptime = 1500;
778
            else beeptime = 200;
779
#endif
780
                NeueKompassRichtungMerken = 5;
781
        carefree_old = CareFree;
782
           } else carefree_old--;
783
        }  
784
        if(FromNaviCtrl.CompassValue < 0 && CareFree) VersionInfo.HardwareError[0] |= FC_ERROR0_CAREFREE; //else VersionInfo.HardwareError[0] &= ~FC_ERROR0_CAREFREE;
785
   }
786
   else
787
   {
788
    CareFree = 0;
789
        carefree_old = 10;
790
   }   
791
 
792
 if(FromNaviCtrl.CompassValue < 0 && MotorenEin && CareFree && BeepMuster == 0xffff) // ungültiger Kompasswert
793
        {
794
         beeptime = 15000;
795
         BeepMuster = 0xA400;
796
         CareFree = 0;
797
    }
798
 if(CareFree) { FC_StatusFlags2 |= FC_STATUS2_CAREFREE; /*if(Parameter_AchsKopplung1 < 210) Parameter_AchsKopplung1 += 30;*/} else FC_StatusFlags2 &= ~FC_STATUS2_CAREFREE;
799
}
800
 
801
void CalcStickGasHover(void)
802
{
803
 if(!EE_Parameter.Hoehe_StickNeutralPoint)
804
        {
805
          StickGasHover = HoverGas/STICK_GAIN; // rescale back to stick value
806
          StickGasHover = (unsigned int)((unsigned int) StickGasHover * UBat) / BattLowVoltageWarning;
807
        }
808
  else StickGasHover = EE_Parameter.Hoehe_StickNeutralPoint;
809
  LIMIT_MIN_MAX(StickGasHover, 70, 175); // reserve some range for trim up and down
810
}
811
 
812
void ChannelAssingment(void)
813
{
814
cli();
815
        ChannelNick = PPM_in[EE_Parameter.Kanalbelegung[K_NICK]];
816
        ChannelRoll = PPM_in[EE_Parameter.Kanalbelegung[K_ROLL]];
817
        ChannelYaw = PPM_in[EE_Parameter.Kanalbelegung[K_GIER]];
818
        ChannelGas = PPM_in[EE_Parameter.Kanalbelegung[K_GAS]];
819
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
820
//+ Analoge Steuerung per Seriell
821
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
822
if((ExternalControl.Config & EC_VALID) && (Parameter_ExternalControl > 128))
823
    {
824
                ChannelNick += ExternalControl.Nick;
825
                ChannelRoll += ExternalControl.Roll;
826
                ChannelYaw += ExternalControl.Gier;
827
        if(ExternalControl.Config & EC_GAS_ADD) ChannelGas += ExternalControl.Gas;
828
                else
829
                 {
830
                  if(ExternalControl.Gas < ChannelGas) ChannelGas = ExternalControl.Gas; // the RC-Stick is the MAX value here
831
             }
832
        }
833
sei();
834
        if(ChannelNick > 127) ChannelNick = 127;        else if(ChannelNick < -127) ChannelNick = -127;
835
        if(ChannelRoll > 127) ChannelRoll = 127;        else if(ChannelRoll < -127) ChannelRoll = -127;
836
        if(ChannelYaw  > 127) ChannelYaw = 127;         else if(ChannelYaw < -127) ChannelYaw = -127;
837
        if(ChannelGas  > 127) ChannelGas = 127;         else if(ChannelGas < -127) ChannelGas = -127;
838
}
839
 
840
//############################################################################
841
//
842
void MotorRegler(void)
843
//############################################################################
844
{
845
         int pd_ergebnis_nick,pd_ergebnis_roll,tmp_int, tmp_int2;
846
         int GierMischanteil,GasMischanteil;
847
     static long sollGier = 0,tmp_long,tmp_long2;
848
         static unsigned int RcLostTimer, delay_Acc_neutral;
849
         static unsigned char delay_neutral = 0;
850
         static unsigned char delay_einschalten = 0,delay_ausschalten = 0;
851
         static signed char move_safety_switch = 0;
852
     int IntegralNickMalFaktor,IntegralRollMalFaktor;
853
         unsigned char i;
854
        Mittelwert();
855
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
856
// Gaswert ermitteln
857
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
858
  if(!(FC_StatusFlags & (FC_STATUS_EMERGENCY_LANDING | FC_STATUS2_RC_FAILSAVE_ACTIVE)))
859
   {
860
        if(EE_Parameter.GlobalConfig3 & CFG3_VARIO_FAILSAFE)
861
        {
862
     if(HoverGas && HoverGas < 150 * STICK_GAIN)
863
           {
864
                HooverGasEmergencyPercent = (HoverGas/(STICK_GAIN) * EE_Parameter.NotGas) / 100; // i.e. 80% of Hovergas
865
           }
866
      else HooverGasEmergencyPercent = 45;  // default if the Hoovergas was could not calculated yet
867
    } else HooverGasEmergencyPercent = EE_Parameter.NotGas;
868
   }
869
   if(GasIsZeroCnt == 30000)  // in that case we have RC-Lost, but the MK is probably landed
870
    {
871
         StickGas = 0; // Hold Gas down in that case 
872
//       ExternalControl.Gas = 0;
873
         HooverGasEmergencyPercent = MIN_GAS;
874
        }
875
        GasMischanteil = StickGas;
876
    if(GasMischanteil < MIN_GAS + 10) GasMischanteil = MIN_GAS + 10;
877
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
878
// Empfang schlecht
879
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
880
   if(SenderOkay < 100 && !(FC_StatusFlags2 & FC_STATUS2_RC_FAILSAVE_ACTIVE))
881
        {
882
                ServoFailsafeActive = SERVO_FS_TIME;
883
        if(RcLostTimer) RcLostTimer--;
884
        else
885
         {
886
          MotorenEin = 0;
887
                  modell_fliegt = 0;
888
          FC_StatusFlags &= ~(FC_STATUS_EMERGENCY_LANDING | FC_STATUS_FLY);
889
         }
890
        ROT_ON;
891
        if(modell_fliegt > 1000 && Capacity.MinOfMaxPWM > 100)  // wahrscheinlich in der Luft --> langsam absenken
892
            {
893
            GasMischanteil = HooverGasEmergencyPercent;
894
            FC_StatusFlags |= FC_STATUS_EMERGENCY_LANDING;
895
            }
896
         else
897
                    {
898
                          MotorenEin = 0;
899
                        }  
900
        }
901
        else
902
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
903
// Emfang gut
904
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
905
        if(SenderOkay > 140)
906
            {
907
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
908
                     static unsigned int trigger = 1000;
909
                         static unsigned char old_switch = 100;
910
                        if(EE_Parameter.StartLandChannel && EE_Parameter.LandingSpeed)
911
                        {
912
                                if(PPM_in[EE_Parameter.StartLandChannel] > 50)
913
                                {
914
                                 if(old_switch == 50) if(FC_StatusFlags2 & FC_STATUS2_WAIT_FOR_TAKEOFF) { FC_StatusFlags2 |= FC_STATUS2_AUTO_STARTING; SpeakHoTT = SPEAK_RISING;}
915
                                 FC_StatusFlags2 &= ~FC_STATUS2_AUTO_LANDING;
916
                                 old_switch = 150;
917
                                }
918
                                else
919
                                if(PPM_in[EE_Parameter.StartLandChannel] < -50)
920
                                {
921
                                 if(old_switch == 150) { FC_StatusFlags2 |= FC_STATUS2_AUTO_LANDING; SpeakHoTT = SPEAK_SINKING;}
922
                                 FC_StatusFlags2 &= ~FC_STATUS2_AUTO_STARTING;
923
                                 old_switch = 50;
924
                                }
925
                                else
926
                                {
927
                                 FC_StatusFlags2 &= ~(FC_STATUS2_AUTO_STARTING | FC_STATUS2_AUTO_LANDING);
928
                                }
929
                        }
930
#endif
931
                        FC_StatusFlags &= ~FC_STATUS_EMERGENCY_LANDING;
932
            RcLostTimer = EE_Parameter.NotGasZeit * 50;
933
            if(GasMischanteil > 40 && MotorenEin)
934
                {
935
                if(modell_fliegt < 0xffff) modell_fliegt++;
936
                }
937
            if((modell_fliegt < 256))
938
             {
939
                SummeNick = 0;
940
                SummeRoll = 0;
941
                sollGier = 0;
942
                Mess_Integral_Gier = 0;
943
                                FC_StatusFlags2 |= FC_STATUS2_WAIT_FOR_TAKEOFF;
944
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
945
                                old_switch = 100;
946
#endif
947
             }
948
                        else
949
                         {
950
               FC_StatusFlags |= FC_STATUS_FLY;
951
                           if(FC_StatusFlags2 & FC_STATUS2_WAIT_FOR_TAKEOFF)
952
                           {
953
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
954
                                if((NC_To_FC_Flags & NC_TO_FC_AUTOSTART || FC_StatusFlags2 & FC_STATUS2_AUTO_STARTING) && (VarioCharacter == '=') && ACC_AltitudeControl)
955
                                {
956
                                   FromNC_AltitudeSpeed = 80;
957
                                   FromNC_AltitudeSetpoint = 500;
958
                                   SollHoehe = 500;
959
                                   trigger = 1000;
960
                                   if(NC_To_FC_Flags & NC_TO_FC_AUTOSTART) SpeakHoTT = SPEAK_NEXT_WP;
961
/*                                 if(StartTrigger != 2)
962
                                                {
963
                                                 StartTrigger = 1;
964
                                                 if(HoverGas < STICK_GAIN * 35) HoverGas = STICK_GAIN * 35;
965
                                                }
966
*/
967
                            }
968
//                              else FC_StatusFlags2 &= ~(FC_STATUS2_AUTO_STARTING);
969
#endif
970
                            if(HoehenWertF > 150 || HoehenWert < -350 || !(Parameter_GlobalConfig & CFG_HOEHENREGELUNG))
971
                                 {
972
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
973
                                  trigger = 1000;
974
                                  if(FC_StatusFlags2 & FC_STATUS2_AUTO_STARTING) { FromNC_AltitudeSpeed = 0; SollHoehe = 300;/*HoehenWertF + 100;*/}
975
                                  else SpeakHoTT = SPEAK_RISING;
976
#endif
977
                                  FC_StatusFlags2 &= ~(FC_STATUS2_WAIT_FOR_TAKEOFF | FC_STATUS2_AUTO_STARTING | FC_STATUS2_AUTO_LANDING);
978
                                 }
979
                SummeNick = 0;
980
                SummeRoll = 0;
981
                Mess_Integral_Gier = 0;
982
//                              sollGier = 0;
983
                                if(modell_fliegt > 1000) modell_fliegt = 1000;  // for the Hooverpoint-Estimation
984
                           }
985
                                else  // Flying mode
986
                                {
987
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
988
                                if((FC_StatusFlags2 & FC_STATUS2_AUTO_LANDING) && (VarioCharacter == 'v' || VarioCharacter == '=') && ACC_AltitudeControl)
989
                                {
990
                                   FromNC_AltitudeSpeed = EE_Parameter.LandingSpeed;
991
                                   FromNC_AltitudeSetpoint = -20000;
992
                            }
993
                                 if(trigger < 1000)
994
                                        {
995
                                                trigger++;
996
                                                SummeNick = 0;
997
                                                SummeRoll = 0;
998
                                                Mess_Integral_Gier = 0;
999
                                                SollHoehe = HoehenWertF - 300;
1000
                                                if(trigger == 1000 && FC_StatusFlags2 & FC_STATUS2_AUTO_LANDING && VarioCharacter != '+')
1001
                                                 {
1002
                                                   FC_StatusFlags2 &= ~FC_STATUS2_AUTO_LANDING;
1003
                                                   FC_StatusFlags2 |= FC_STATUS2_WAIT_FOR_TAKEOFF;  // go back into starting state
1004
                                             } 
1005
                                        }
1006
                                 else
1007
                                 if(ACC_AltitudeControl && (VarioCharacter == 'v' || VarioCharacter == '-') && HoehenWert < 1000 /*&& FromNC_AltitudeSetpoint < 0*/)
1008
                                  {
1009
                                        if((Aktuell_az/4 > EE_Parameter.LandingPulse) && (NeutralAccZ/4 > EE_Parameter.LandingPulse))
1010
                                         {
1011
                                          trigger = 0;
1012
                                          SpeakHoTT = SPEAK_LANDING;
1013
                                         };
1014
                                  }
1015
#endif
1016
               }
1017
                          }  // end of: modell_fliegt > 256                        
1018
            if((ChannelGas > 80) && MotorenEin == 0 && !(NC_To_FC_Flags & NC_TO_FC_SIMULATION_ACTIVE))
1019
                {
1020
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1021
// auf Nullwerte kalibrieren
1022
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1023
                if(ChannelYaw > 75)  // Neutralwerte
1024
                    {
1025
                    if(++delay_neutral > 200)  // nicht sofort
1026
                        {
1027
                        unsigned char setting = 0;
1028
                        delay_neutral = 0;
1029
                        modell_fliegt = 0;
1030
                        if(ChannelNick > 70 || abs(ChannelRoll) > 70)
1031
                        {
1032
                         if(ChannelRoll > 70 && ChannelNick < 70 && ChannelNick > -70) setting = 1;
1033
                         if(ChannelRoll > 70 && ChannelNick > 70) setting = 2;
1034
                         if(ChannelRoll < 70 && ChannelNick > 70) setting = 3;
1035
                         if(ChannelRoll <-70 && ChannelNick > 70) setting = 4;
1036
                         if(ChannelRoll <-70 && ChannelNick < 70  && ChannelNick > -70) setting = 5;
1037
                         if(setting) SetActiveParamSet(setting);  // aktiven Datensatz merken
1038
                        }
1039
                         if(abs(ChannelRoll) < 30 && ChannelNick < -70)
1040
                          {
1041
                           WinkelOut.CalcState = 1; // Compass kalibrieren
1042
                                                   CalibrationDone = 0;
1043
                           beeptime = 1000;
1044
                          }
1045
                          else
1046
                          {
1047
                               ParamSet_ReadFromEEProm(ActiveParamSet);
1048
                               LipoDetection(0);
1049
                                                   LIBFC_ReceiverInit(EE_Parameter.Receiver);
1050
                           if((Parameter_GlobalConfig & CFG_HOEHENREGELUNG))  // Höhenregelung aktiviert?
1051
                            {
1052
                             if((MessLuftdruck > 950) || (MessLuftdruck < 750)) SucheLuftruckOffset();
1053
                            }
1054
                           if(!setting && ChannelRoll < -70 && ChannelNick < 70) CalibrationDone = SetNeutral(3); // Boat-Mode
1055
//                                                 else
1056
//                                                 if(!setting && ChannelYaw < -75 && abs(ChannelNick) < 70)  CalibrationDone = SetNeutral(2); // store ACC values into EEPROM
1057
                                                   else    CalibrationDone = SetNeutral(1);
1058
                                                   ServoActive = 1;
1059
                                                   DDRD  |=0x80; // enable J7 -> Servo signal
1060
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
1061
                                                   if(VersionInfo.HardwareError[0]) SpeakHoTT = SPEAK_ERR_SENSOR;
1062
                                                   else
1063
                                                   if(!CalibrationDone) SpeakHoTT = SPEAK_ERR_CALIBARTION;
1064
                                                   else SpeakHoTT = SPEAK_CALIBRATE;
1065
                                                   ShowSettingNameTime = 10; // for HoTT & Jeti 
1066
#endif
1067
                           Piep(ActiveParamSet,120);
1068
                         }
1069
                        }
1070
                    }
1071
                                        else
1072
                    if(ChannelYaw < -75 && abs(ChannelRoll) < 16 && abs(ChannelRoll) < 16)  // ACC calibrate
1073
                     {                      
1074
                     if(++delay_Acc_neutral > 500 * 5)  // 5 sekunden
1075
                        {
1076
                          delay_Acc_neutral = 0;
1077
                                                  CalibrationDone = SetNeutral(2); // store ACC values into EEPROM
1078
                                                  ServoActive = 1;
1079
                                                  DDRD  |=0x80; // enable J7 -> Servo signal
1080
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
1081
                                                   if(VersionInfo.HardwareError[0]) SpeakHoTT = SPEAK_ERR_SENSOR;
1082
                                                   else
1083
                                                   if(!CalibrationDone) SpeakHoTT = SPEAK_ERR_CALIBARTION;
1084
                                                   else SpeakHoTT = SPEAK_CALIBRATE;
1085
                                                   ShowSettingNameTime = 10; // for HoTT & Jeti 
1086
#endif
1087
                           Piep(ActiveParamSet,120);
1088
                         }
1089
                     }
1090
                  else { delay_neutral = 0; delay_Acc_neutral = 0;};
1091
                }
1092
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1093
// Gas ist unten
1094
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1095
            if(ChannelGas < -100)
1096
                {
1097
                                        if(PPM_diff[EE_Parameter.MotorSafetySwitch & 127] > 5) move_safety_switch = 100;
1098
                                        else
1099
                                        if(PPM_diff[EE_Parameter.MotorSafetySwitch & 127] < -5) move_safety_switch = -100;
1100
                                        // Motoren Starten
1101
                                        if(!MotorenEin)
1102
                        {
1103
                                                if(((((ChannelYaw < -100) && ((!(EE_Parameter.GlobalConfig3 & CFG3_MOTOR_SWITCH_MODE) && PPM_in[EE_Parameter.MotorSafetySwitch] < -75) || EE_Parameter.MotorSafetySwitch == 0)))
1104
                                                || (((EE_Parameter.GlobalConfig3 & CFG3_MOTOR_SWITCH_MODE) && PPM_in[EE_Parameter.MotorSafetySwitch] > -10 && move_safety_switch == 100)))
1105
                                                && !(NC_To_FC_Flags & NC_TO_FC_SIMULATION_ACTIVE))  
1106
                                                {
1107
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1108
// Einschalten
1109
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1110
                                                        if(CalibrationDone) FC_StatusFlags |= FC_STATUS_START;
1111
 
1112
                                                        StartLuftdruck = Luftdruck;
1113
                                                        HoehenWert = 0;
1114
                                                        HoehenWert_Mess = 0;
1115
                                                        GasIsZeroCnt = 600;
1116
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
1117
                                                        HoehenWertF_Mess = 0;
1118
#endif
1119
                                                        SummenHoehe = 0;
1120
                                                        if((ChannelNick > -100 || abs(ChannelRoll) < 100) && EE_Parameter.MotorSafetySwitch == 0) delay_einschalten = 0;
1121
                                                        if(++delay_einschalten > 253)
1122
                                                        {
1123
if(FC_StatusFlags3 & FC_STATUS3_BOAT) { if((abs(MesswertGier) > 32*2 || abs(MesswertNick) > 20*3) || abs(MesswertRoll) > 20*3)  CalibrationDone = 0; } // dann ist der Gyro defekt, schlecht kalibriert oder der MK dreht sich
1124
else
1125
                                                                if((abs(MesswertGier) > 32 || abs(MesswertNick) > 20) || abs(MesswertRoll) > 20)  CalibrationDone = 0; // dann ist der Gyro defekt, schlecht kalibriert oder der MK dreht sich
1126
                                                                delay_einschalten = 0;
1127
                                                                if(!VersionInfo.HardwareError[0] && CalibrationDone && !NC_ErrorCode)
1128
                                                                {
1129
                                                                        modell_fliegt = 1;
1130
                                                                        MotorenEin = 1;
1131
                                                                        sollGier = 0;
1132
                                                                        Mess_Integral_Gier = 0;
1133
                                                                        Mess_Integral_Gier2 = 0;
1134
                                                                        Mess_IntegralNick = EE_Parameter.GyroAccFaktor * (long)Mittelwert_AccNick;
1135
                                                                        Mess_IntegralRoll = EE_Parameter.GyroAccFaktor * (long)Mittelwert_AccRoll;
1136
                                                                        SummeNick = 0;
1137
                                                                        SummeRoll = 0;
1138
//                                                                      ControlHeading = (((int) EE_Parameter.OrientationAngle * 15 + KompassValue) % 360) / 2;
1139
                                                                        NeueKompassRichtungMerken = 100; // 2 sekunden
1140
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
1141
                                                                        SpeakHoTT = SPEAK_STARTING;
1142
#endif
1143
                                                                }
1144
                                                                else
1145
                                                                {
1146
                                                                        beeptime = 1500; // indicate missing calibration
1147
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
1148
                                                                        if(!CalibrationDone) SpeakHoTT = SPEAK_ERR_CALIBARTION;
1149
#endif
1150
                                                                }
1151
                                                        }
1152
                                                }
1153
                                                else delay_einschalten = 0;
1154
                                        }
1155
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1156
// Auschalten
1157
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1158
                                        else // only if motors are running
1159
                                        {
1160
//                                              if((PPM_in[EE_Parameter.Kanalbelegung[K_GIER]] > 75) && (PPM_in[EE_Parameter.MotorSafetySwitch] < -75 || EE_Parameter.MotorSafetySwitch == 0))
1161
                                                if((((ChannelYaw > 100) && ((!(EE_Parameter.GlobalConfig3 & CFG3_MOTOR_SWITCH_MODE) && PPM_in[EE_Parameter.MotorSafetySwitch] < -75) || EE_Parameter.MotorSafetySwitch == 0)))
1162
                                                || (((EE_Parameter.GlobalConfig3 & CFG3_MOTOR_SWITCH_MODE) && PPM_in[EE_Parameter.MotorSafetySwitch] < -50 && move_safety_switch == -100)))
1163
                                                {
1164
                                                        if((ChannelNick > -100 || abs(ChannelRoll) < 100) && EE_Parameter.MotorSafetySwitch == 0)
1165
                                                        {
1166
                                                                delay_ausschalten = 0;
1167
                                                        }
1168
                                                        else
1169
                                                        {
1170
                                                          SummeNick = 0;
1171
                                                          SummeRoll = 0;
1172
                                                          StickNick = 0;
1173
                                                          StickRoll = 0;
1174
                                                        }
1175
                                                        if(++delay_ausschalten > 250)  // nicht sofort
1176
                                                        {
1177
                                                                MotorenEin = 0;
1178
                                                                delay_ausschalten = 0;
1179
                                                                modell_fliegt = 0;
1180
                                                                FC_StatusFlags2 &= ~(FC_STATUS2_WAIT_FOR_TAKEOFF | FC_STATUS2_AUTO_STARTING | FC_STATUS2_AUTO_LANDING);
1181
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
1182
                                                                SpeakHoTT = SPEAK_MK_OFF;
1183
#endif
1184
                                                        }
1185
                                                        else
1186
                                                         if(delay_ausschalten == 100) beeptime = 3500;
1187
                                                }
1188
                                                else delay_ausschalten = 0;
1189
                                        }
1190
                  if(GasIsZeroCnt < 1000)
1191
                                   {
1192
                                    if(VarioMeter > -150) GasIsZeroCnt++;
1193
                                        else if(GasIsZeroCnt) GasIsZeroCnt--;
1194
                                   }   
1195
                                }
1196
                                else // gas not at minimum
1197
                                {
1198
                                  move_safety_switch = 0;
1199
                                  GasIsZeroCnt = 0;
1200
                                }  
1201
            }
1202
                        else  // Empfang zwischen 100 und 140 -> schlecht
1203
                        {
1204
                        if(GasIsZeroCnt >= 750)  // gas-stick was down for 1.5 seconds before RC-Lost
1205
                         {
1206
                           if((GPSInfo.HomeDistance < 40 * 10) && (HoehenWert < 15 * 100))  // and we are at the starting point -> maybe landed? 
1207
                                {
1208
                                 GasIsZeroCnt = 30000;
1209
                                 if(modell_fliegt > 1001) modell_fliegt = 1001;
1210
                                }        
1211
                         }
1212
                        }
1213
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1214
// neue Werte von der Funke
1215
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1216
 
1217
 if(!NewPpmData-- || (FC_StatusFlags & FC_STATUS_EMERGENCY_LANDING))
1218
  {
1219
        static int stick_nick,stick_roll;
1220
        unsigned char stick_p;
1221
    ParameterZuordnung();
1222
        ChannelAssingment();
1223
 
1224
        stick_p = EE_Parameter.Stick_P;
1225
    stick_nick = (stick_nick * 3 + ChannelNick * stick_p) / 4;
1226
    stick_roll = (stick_roll * 3 + ChannelRoll * stick_p) / 4;
1227
cli();
1228
    stick_nick += PPM_diff[EE_Parameter.Kanalbelegung[K_NICK]] * EE_Parameter.Stick_D;
1229
    stick_roll += PPM_diff[EE_Parameter.Kanalbelegung[K_ROLL]] * EE_Parameter.Stick_D;
1230
sei();
1231
        StickGas  = ChannelGas + 127;
1232
 
1233
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1234
// CareFree und freie Wahl der vorderen Richtung
1235
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1236
        if(CareFree)
1237
        {
1238
                signed int nick, roll;
1239
                nick = stick_nick / 4;
1240
                roll = stick_roll / 4;
1241
                StickNick = ((FromNC_Rotate_C * nick) + (FromNC_Rotate_S * roll)) / (32 / 4);
1242
                StickRoll = ((FromNC_Rotate_C * roll) - (FromNC_Rotate_S * nick)) / (32 / 4);
1243
        }
1244
        else
1245
        {
1246
                FromNC_Rotate_C = sintab[EE_Parameter.OrientationAngle + 6];
1247
                FromNC_Rotate_S = sintab[EE_Parameter.OrientationAngle];
1248
                StickNick = ((FromNC_Rotate_C * stick_nick) + (FromNC_Rotate_S * stick_roll)) / 8;
1249
                StickRoll = ((FromNC_Rotate_C * stick_roll) - (FromNC_Rotate_S * stick_nick)) / 8;
1250
        }
1251
 
1252
    StickGier = -ChannelYaw;
1253
        if(StickGier > 4) StickGier -= 4;       else
1254
        if(StickGier < -4) StickGier += 4; else StickGier = 0;
1255
 
1256
if(GasIsZeroCnt > 512) // About to switch - off
1257
 {
1258
  StickNick = StickNick/8;
1259
  StickRoll = StickRoll/8;  
1260
  SummeNick = 0;
1261
  SummeRoll = 0;
1262
 }
1263
else
1264
    if(GPS_Aid_StickMultiplikator) // in that case the GPS controls stronger
1265
         {
1266
          StickNick = (GPS_Aid_StickMultiplikator * (StickNick / 8)) / 16;
1267
          StickRoll = (GPS_Aid_StickMultiplikator * (StickRoll / 8)) / 16;
1268
         }
1269
    StickNick -= GPS_Nick;
1270
    StickRoll -= GPS_Roll;
1271
 
1272
    GyroFaktor     = (Parameter_Gyro_P + 10.0);
1273
    IntegralFaktor = Parameter_Gyro_I;
1274
    GyroFaktorGier     = (Parameter_Gyro_Gier_P + 10.0);
1275
    IntegralFaktorGier = Parameter_Gyro_Gier_I;
1276
 
1277
 
1278
    if(Parameter_GlobalConfig & CFG_HEADING_HOLD) IntegralFaktor =  0;
1279
 
1280
    if(abs(StickNick/STICK_GAIN) > MaxStickNick)
1281
     {
1282
      MaxStickNick = abs(StickNick)/STICK_GAIN;
1283
      if(MaxStickNick > 100) MaxStickNick = 100;
1284
     }
1285
     else MaxStickNick--;
1286
    if(abs(StickRoll/STICK_GAIN) > MaxStickRoll)
1287
     {
1288
      MaxStickRoll = abs(StickRoll)/STICK_GAIN;
1289
      if(MaxStickRoll > 100) MaxStickRoll = 100;
1290
     }
1291
     else MaxStickRoll--;
1292
    if(FC_StatusFlags & FC_STATUS_EMERGENCY_LANDING)  {MaxStickNick = 0; MaxStickRoll = 0;}
1293
 
1294
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1295
// Looping?
1296
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1297
  if((PPM_in[EE_Parameter.Kanalbelegung[K_ROLL]] > EE_Parameter.LoopThreshold) && EE_Parameter.BitConfig & CFG_LOOP_LINKS)  Looping_Links = 1;
1298
  else
1299
   {
1300
     {
1301
      if((PPM_in[EE_Parameter.Kanalbelegung[K_ROLL]] < (EE_Parameter.LoopThreshold - EE_Parameter.LoopHysterese))) Looping_Links = 0;
1302
     }
1303
   }
1304
  if((PPM_in[EE_Parameter.Kanalbelegung[K_ROLL]] < -EE_Parameter.LoopThreshold) && EE_Parameter.BitConfig & CFG_LOOP_RECHTS) Looping_Rechts = 1;
1305
   else
1306
   {
1307
   if(Looping_Rechts) // Hysterese
1308
     {
1309
      if(PPM_in[EE_Parameter.Kanalbelegung[K_ROLL]] > -(EE_Parameter.LoopThreshold - EE_Parameter.LoopHysterese)) Looping_Rechts = 0;
1310
     }
1311
   }
1312
 
1313
  if((PPM_in[EE_Parameter.Kanalbelegung[K_NICK]] > EE_Parameter.LoopThreshold) && EE_Parameter.BitConfig & CFG_LOOP_OBEN) Looping_Oben = 1;
1314
  else
1315
   {
1316
    if(Looping_Oben)  // Hysterese
1317
     {
1318
      if((PPM_in[EE_Parameter.Kanalbelegung[K_NICK]] < (EE_Parameter.LoopThreshold - EE_Parameter.LoopHysterese))) Looping_Oben = 0;
1319
     }
1320
   }
1321
  if((PPM_in[EE_Parameter.Kanalbelegung[K_NICK]] < -EE_Parameter.LoopThreshold) && EE_Parameter.BitConfig & CFG_LOOP_UNTEN) Looping_Unten = 1;
1322
   else
1323
   {
1324
    if(Looping_Unten) // Hysterese
1325
     {
1326
      if(PPM_in[EE_Parameter.Kanalbelegung[K_NICK]] > -(EE_Parameter.LoopThreshold - EE_Parameter.LoopHysterese)) Looping_Unten = 0;
1327
     }
1328
   }
1329
 
1330
   if(Looping_Links || Looping_Rechts)   Looping_Roll = 1; else Looping_Roll = 0;
1331
   if(Looping_Oben  || Looping_Unten) {  Looping_Nick = 1; Looping_Roll = 0; Looping_Links = 0; Looping_Rechts = 0;} else Looping_Nick = 0;
1332
  } // Ende neue Funken-Werte
1333
 
1334
  if(Looping_Roll || Looping_Nick)
1335
   {
1336
    if(GasMischanteil > EE_Parameter.LoopGasLimit) GasMischanteil = EE_Parameter.LoopGasLimit;
1337
        TrichterFlug = 1;
1338
   }
1339
 
1340
 
1341
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1342
// Bei Empfangsausfall im Flug
1343
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1344
   if(FC_StatusFlags2 & FC_STATUS2_RC_FAILSAVE_ACTIVE)
1345
   {
1346
    StickNick = -GPS_Nick;
1347
    StickRoll = -GPS_Roll;
1348
        StickGas = StickGasHover;
1349
    StickGier = 0;
1350
        Parameter_GlobalConfig &= ~(CFG_HEADING_HOLD | CFG_DREHRATEN_BEGRENZER);
1351
        Parameter_GlobalConfig |= CFG_HOEHENREGELUNG | CFG_ACHSENKOPPLUNG_AKTIV | CFG_KOMPASS_AKTIV | CFG_GPS_AKTIV | CFG_HOEHEN_SCHALTER | CFG_GPS_AKTIV;
1352
        Parameter_ExtraConfig &= ~(CFG2_HEIGHT_LIMIT | CFG_LEARNABLE_CAREFREE | CFG2_VARIO_BEEP);
1353
        Parameter_HoehenSchalter = 200; // switch on
1354
   }
1355
   else
1356
   if(FC_StatusFlags & FC_STATUS_EMERGENCY_LANDING)
1357
    {
1358
     StickGier = 0;
1359
     StickNick = 0;
1360
     StickRoll = 0;
1361
     GyroFaktor     = 90;
1362
     IntegralFaktor = 120;
1363
     GyroFaktorGier     = 90;
1364
     IntegralFaktorGier = 120;
1365
     Looping_Roll = 0;
1366
     Looping_Nick = 0;
1367
    }
1368
 
1369
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1370
// Integrale auf ACC-Signal abgleichen
1371
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1372
#define ABGLEICH_ANZAHL 256L
1373
 
1374
 MittelIntegralNick  += IntegralNick;    // Für die Mittelwertbildung aufsummieren
1375
 MittelIntegralRoll  += IntegralRoll;
1376
 if(Looping_Nick || Looping_Roll)
1377
  {
1378
    MittelIntegralNick = 0;
1379
    MittelIntegralRoll = 0;
1380
    ZaehlMessungen = 0;
1381
    LageKorrekturNick = 0;
1382
    LageKorrekturRoll = 0;
1383
  }
1384
 
1385
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1386
  if(!Looping_Nick && !Looping_Roll && (Aktuell_az > 512 || MotorenEin))
1387
  {
1388
   long tmp_long, tmp_long2;
1389
   if(FromNaviCtrl_Value.Kalman_K > 0 /*&& !TrichterFlug*/)
1390
     {
1391
                tmp_long = (long)(IntegralNick / EE_Parameter.GyroAccFaktor - (long)(Mittelwert_AccNick - FromNaviCtrl.AccErrorN));
1392
                tmp_long2 = (long)(IntegralRoll / EE_Parameter.GyroAccFaktor - (long)(Mittelwert_AccRoll - FromNaviCtrl.AccErrorR));
1393
                tmp_long  = (tmp_long  * FromNaviCtrl_Value.Kalman_K) / (32 * 16);
1394
                tmp_long2 = (tmp_long2 * FromNaviCtrl_Value.Kalman_K) / (32 * 16);
1395
                if((MaxStickNick > 64) || (MaxStickRoll > 64))
1396
                {
1397
                tmp_long  /= 2;
1398
                tmp_long2 /= 2;
1399
                }
1400
                if(tmp_long >  (long) FromNaviCtrl_Value.Kalman_MaxFusion)  tmp_long  = (long) FromNaviCtrl_Value.Kalman_MaxFusion;
1401
                if(tmp_long <  (long)-FromNaviCtrl_Value.Kalman_MaxFusion)  tmp_long  = (long)-FromNaviCtrl_Value.Kalman_MaxFusion;
1402
                if(tmp_long2 > (long) FromNaviCtrl_Value.Kalman_MaxFusion)  tmp_long2 = (long) FromNaviCtrl_Value.Kalman_MaxFusion;
1403
                if(tmp_long2 < (long)-FromNaviCtrl_Value.Kalman_MaxFusion)  tmp_long2 = (long)-FromNaviCtrl_Value.Kalman_MaxFusion;
1404
     }
1405
     else
1406
     {
1407
                tmp_long = (long)(IntegralNick / EE_Parameter.GyroAccFaktor - (long)Mittelwert_AccNick);
1408
                tmp_long2 = (long)(IntegralRoll / EE_Parameter.GyroAccFaktor - (long)Mittelwert_AccRoll);
1409
                tmp_long /= 16;
1410
                tmp_long2 /= 16;
1411
                if((MaxStickNick > 64) || (MaxStickRoll > 64))
1412
                {
1413
                tmp_long  /= 3;
1414
                tmp_long2 /= 3;
1415
                }
1416
                if(abs(ChannelYaw) > 25)
1417
                {
1418
                tmp_long  /= 3;
1419
                tmp_long2 /= 3;
1420
                }
1421
                KompassFusion = 25;
1422
#define AUSGLEICH  32
1423
                if(tmp_long >  AUSGLEICH)  tmp_long  = AUSGLEICH;
1424
                if(tmp_long < -AUSGLEICH)  tmp_long  =-AUSGLEICH;
1425
                if(tmp_long2 > AUSGLEICH)  tmp_long2 = AUSGLEICH;
1426
                if(tmp_long2 <-AUSGLEICH)  tmp_long2 =-AUSGLEICH;
1427
     }
1428
 
1429
        Mess_IntegralNick -= tmp_long;
1430
        Mess_IntegralRoll -= tmp_long2;
1431
        DriftNick += tmp_long;
1432
        DriftRoll += tmp_long2;
1433
  }
1434
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1435
 if(ZaehlMessungen >= ABGLEICH_ANZAHL)  //alle 512ms
1436
 {
1437
//  static int cnt = 0;
1438
//  static char last_n_p,last_n_n,last_r_p,last_r_n;
1439
  static long MittelIntegralNick_Alt,MittelIntegralRoll_Alt;
1440
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1441
// Gyro-Drift ermitteln
1442
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1443
  if(EE_Parameter.Driftkomp && abs(Mittelwert_AccNick) < 200*4 && abs(Mittelwert_AccRoll) < 200*4 && !TrichterFlug && abs(MesswertGier) < 32/* && (FC_StatusFlags & FC_STATUS_FLY)*/)
1444
  {
1445
   DriftNick -= DriftNick / (64 * (unsigned int) EE_Parameter.Driftkomp);
1446
   DriftRoll -= DriftRoll / (64 * (unsigned int) EE_Parameter.Driftkomp);
1447
   GierGyroFehler -= GierGyroFehler / (64 * (unsigned int) EE_Parameter.Driftkomp);
1448
   if((MaxStickNick > 64) || (MaxStickRoll > 64) || (abs(ChannelYaw) > 25))
1449
    {
1450
     DriftNick /= 2;
1451
     DriftRoll /= 2;
1452
         GierGyroFehler = 0;
1453
    }
1454
         if(DriftNick > 3000) { DriftNick = 0; AdNeutralNick++;}
1455
         if(DriftNick <-3000) { DriftNick = 0; AdNeutralNick--;}
1456
         if(DriftRoll > 3000) { DriftRoll = 0; AdNeutralRoll++;}
1457
         if(DriftRoll <-3000) { DriftRoll = 0; AdNeutralRoll--;}
1458
     if(GierGyroFehler > 3500) { GierGyroFehler = 0; AdNeutralGier++; }
1459
     if(GierGyroFehler <-3500) { GierGyroFehler = 0; AdNeutralGier--; }
1460
  }
1461
  else
1462
  {
1463
   DriftNick = 0;
1464
   DriftRoll = 0;
1465
   GierGyroFehler = 0;
1466
  }
1467
  TrichterFlug = 0;
1468
 
1469
  if(!IntegralFaktor) { LageKorrekturRoll = 0; LageKorrekturNick = 0;} // z.B. bei HH
1470
// +++++++++++++++++++++++++++++++++++++++++++++++++++++
1471
   MittelIntegralNick_Alt = MittelIntegralNick;
1472
   MittelIntegralRoll_Alt = MittelIntegralRoll;
1473
// +++++++++++++++++++++++++++++++++++++++++++++++++++++
1474
    MittelIntegralNick = 0;
1475
    MittelIntegralRoll = 0;
1476
    ZaehlMessungen = 0;
1477
 } //  ZaehlMessungen >= ABGLEICH_ANZAHL
1478
 
1479
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1480
//  Gieren
1481
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1482
    if(abs(StickGier) > 3) // war 15
1483
     {
1484
//      KompassSignalSchlecht = 1000;
1485
      if(!(Parameter_GlobalConfig & CFG_KOMPASS_FIX))
1486
       {
1487
         NeueKompassRichtungMerken = 50; // eine Sekunde zum Einloggen
1488
        };
1489
     }
1490
    tmp_int  = (long) EE_Parameter.StickGier_P * ((long)StickGier * abs(StickGier)) / 512L; // expo  y = ax + bx²
1491
    tmp_int += (EE_Parameter.StickGier_P * StickGier) / 4;
1492
        if(GasIsZeroCnt > 512) tmp_int = 0; // disable Yawing when Gas-Stick is to Zero
1493
        tmp_int += CompassGierSetpoint;
1494
    sollGier = tmp_int;
1495
    Mess_Integral_Gier -= tmp_int;
1496
    if(Mess_Integral_Gier > 50000) Mess_Integral_Gier = 50000;  // begrenzen
1497
    if(Mess_Integral_Gier <-50000) Mess_Integral_Gier =-50000;
1498
 
1499
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1500
//  Kompass
1501
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1502
    if(KompassValue >= 0 && (Parameter_GlobalConfig & CFG_KOMPASS_AKTIV))
1503
     {
1504
      if(CalculateCompassTimer-- == 1)
1505
          {
1506
       int w,v,r,fehler,korrektur; // wird von der SPI-Routine auf 1 gesetzt
1507
       CalculateCompassTimer = 13; // falls keine Navi-Daten
1508
           // max. Korrekturwert schätzen
1509
       w = abs(IntegralNick /512); // mit zunehmender Neigung den Einfluss drosseln
1510
       v = abs(IntegralRoll /512);
1511
       if(v > w) w = v; // grösste Neigung ermitteln
1512
//       korrektur = w / 4 + 1;
1513
           korrektur = w / 8 + 2;
1514
           ErsatzKompassInGrad = ErsatzKompass/GIER_GRAD_FAKTOR;
1515
           // Kompassfehlerwert bestimmen   
1516
           fehler = ((540 + KompassValue - ErsatzKompassInGrad) % 360) - 180;
1517
           // GIER_GRAD_FAKTOR ist ca. 1200
1518
           // Kompasswert einloggen
1519
       if(NeueKompassRichtungMerken) KompassSollWert = ErsatzKompassInGrad;
1520
 
1521
       if(KompassSignalSchlecht) KompassSignalSchlecht--;
1522
           else
1523
       if(w < 25)
1524
        {
1525
        GierGyroFehler += fehler;
1526
                if(NeueKompassRichtungMerken) NeueKompassRichtungMerken--;
1527
        }
1528
       // Kompass fusionieren
1529
       if(!KompassSignalSchlecht) ErsatzKompass += (fehler * KompassFusion) / korrektur;
1530
       // MK Gieren
1531
           if(!NeueKompassRichtungMerken)
1532
       {
1533
           r = ((540 + (KompassSollWert - ErsatzKompassInGrad)) % 360) - 180;
1534
           v = r * (Parameter_KompassWirkung/2);  // nach Kompass ausrichten
1535
                   CompassGierSetpoint = v / 16;
1536
       }
1537
      else CompassGierSetpoint = 0;
1538
      } // CalculateCompassTimer
1539
     }
1540
         else CompassGierSetpoint = 0;
1541
 
1542
//DebugOut.Analog[16] = KompassFusion;
1543
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1544
//  Drehgeschwindigkeit und -winkel zu einem Istwert zusammenfassen
1545
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1546
  if(TrichterFlug)  { SummeRoll = 0; SummeNick = 0;};
1547
 
1548
  if(!Looping_Nick) IntegralNickMalFaktor = (IntegralNick * IntegralFaktor) /  (44000 / STICK_GAIN); else IntegralNickMalFaktor = 0;
1549
  if(!Looping_Roll) IntegralRollMalFaktor = (IntegralRoll * IntegralFaktor) /  (44000 / STICK_GAIN); else IntegralRollMalFaktor = 0;
1550
 
1551
#define TRIM_MAX 200
1552
 if(TrimNick > TRIM_MAX) TrimNick = TRIM_MAX; else  if(TrimNick <-TRIM_MAX) TrimNick =-TRIM_MAX;
1553
 if(TrimRoll > TRIM_MAX) TrimRoll = TRIM_MAX; else  if(TrimRoll <-TRIM_MAX) TrimRoll =-TRIM_MAX;
1554
 
1555
    MesswertNick = IntegralNickMalFaktor + (long)((long)MesswertNick * GyroFaktor + (long)TrimNick * 128L) / (256L / STICK_GAIN);
1556
    MesswertRoll = IntegralRollMalFaktor + (long)((long)MesswertRoll * GyroFaktor + (long)TrimRoll * 128L) / (256L / STICK_GAIN);
1557
    MesswertGier = (long)(MesswertGier * 2 * (long)GyroFaktorGier) / (256L / STICK_GAIN) + (long)(Integral_Gier * IntegralFaktorGier) / (2 * (44000 / STICK_GAIN));
1558
 
1559
    // Maximalwerte abfangen
1560
    #define MAX_SENSOR  (4096)
1561
    if(MesswertNick >  MAX_SENSOR) MesswertNick =  MAX_SENSOR;
1562
    if(MesswertNick < -MAX_SENSOR) MesswertNick = -MAX_SENSOR;
1563
    if(MesswertRoll >  MAX_SENSOR) MesswertRoll =  MAX_SENSOR;
1564
    if(MesswertRoll < -MAX_SENSOR) MesswertRoll = -MAX_SENSOR;
1565
    if(MesswertGier >  MAX_SENSOR) MesswertGier =  MAX_SENSOR;
1566
    if(MesswertGier < -MAX_SENSOR) MesswertGier = -MAX_SENSOR;
1567
 
1568
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1569
// Undervoltage
1570
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1571
  if(!(FC_StatusFlags & FC_STATUS_LOWBAT))
1572
  {
1573
    GasMischanteil = ((unsigned int)GasMischanteil * BattLowVoltageWarning) / UBat; // Gas auf das aktuelle Spannungvieveau beziehen
1574
  }
1575
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1576
// Auto-Landing
1577
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1578
 static unsigned char slower;
1579
 if(!slower--)
1580
  {
1581
   static unsigned int u_filter = 0;
1582
   if(!u_filter) u_filter = UBat;
1583
   if(UBat > u_filter) u_filter++; else
1584
   if(UBat < u_filter) u_filter--;
1585
   slower = 100; // 5Hz
1586
   if(u_filter < BattAutoLandingVoltage)
1587
         {
1588
          LowVoltageLandingActive = 10; // 2 sek
1589
          ServoFailsafeActive = SERVO_FS_TIME;
1590
         }
1591
         else if(u_filter > BattAutoLandingVoltage + LipoCells && LowVoltageLandingActive) LowVoltageLandingActive--;
1592
 
1593
   if(u_filter < BattComingHomeVoltage)
1594
         {
1595
          LowVoltageHomeActive = 25; // min. 5 sek
1596
         }
1597
         else if(u_filter > BattComingHomeVoltage + LipoCells && LowVoltageHomeActive) LowVoltageHomeActive--;
1598
  }
1599
  if(LowVoltageLandingActive && FromNC_AltitudeSetpoint >= 0)
1600
     {
1601
                FromNC_AltitudeSpeed = EE_Parameter.LandingSpeed;
1602
                if(HoehenWert > 15*100) FromNC_AltitudeSpeed *= 2; // faster above 15m
1603
                FromNC_AltitudeSetpoint = -20000;
1604
         }
1605
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1606
// send SPI pending bytes
1607
 if(BytegapSPI == 0)  SPI_TransmitByte();
1608
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1609
// Höhenregelung
1610
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1611
  GasMischanteil *= STICK_GAIN;
1612
// if height control is activated
1613
 if((Parameter_GlobalConfig & CFG_HOEHENREGELUNG) && !(Looping_Roll || Looping_Nick) && !(VersionInfo.HardwareError[0] & 0x7F))  // Höhenregelung
1614
        {
1615
                #define HOVER_GAS_AVERAGE 16384L                // 16384 * 2ms = 32s averaging
1616
                #define HC_GAS_AVERAGE 4                        // 4 * 2ms= 8ms averaging
1617
 
1618
                int HCGas, GasReduction = 0;
1619
                static int HeightTrimming = 0;  // rate for change of height setpoint
1620
                static int HeightDeviation = 0, FilterHCGas = 0;
1621
                static unsigned long HoverGasFilter = 0;
1622
                static unsigned char delay = 100, BaroAtUpperLimit = 0, BaroAtLowerLimit = 0;
1623
        // Expand the measurement
1624
                // measurement of air pressure close to upper limit and no overflow in correction of the new OCR0A value occurs
1625
          if(!BaroExpandActive)
1626
                   {
1627
                        if(MessLuftdruck > 920)
1628
                        {   // increase offset
1629
             if(OCR0A < (255 - OPA_OFFSET_STEP))
1630
                           {
1631
                                ExpandBaro -= 1;
1632
                                OCR0A = DruckOffsetSetting - OPA_OFFSET_STEP * ExpandBaro; // increase offset to shift ADC down
1633
                                OCR0B = 255 - OCR0A;
1634
                                beeptime = 300;
1635
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
1636
                                if(ACC_AltitudeControl) BaroExpandActive = 50;
1637
                                else
1638
#endif
1639
                BaroExpandActive = 350;
1640
                                CalcExpandBaroStep();
1641
                           }
1642
                           else
1643
                           {
1644
                            BaroAtLowerLimit = 1;
1645
               }
1646
                        }
1647
                        // measurement of air pressure close to lower limit and
1648
                        else
1649
                        if(MessLuftdruck < 100)
1650
                        {   // decrease offset
1651
                          if(OCR0A > OPA_OFFSET_STEP)
1652
                           {
1653
                                ExpandBaro += 1;
1654
                                OCR0A = DruckOffsetSetting - OPA_OFFSET_STEP * ExpandBaro; // decrease offset to shift ADC up
1655
                                OCR0B = 255 - OCR0A;
1656
                                beeptime = 300;
1657
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
1658
                                if(ACC_AltitudeControl) BaroExpandActive = 50;
1659
                                else
1660
#endif
1661
                BaroExpandActive = 350;
1662
                                CalcExpandBaroStep();
1663
                           }
1664
                           else
1665
                           {
1666
                            BaroAtUpperLimit = 1;
1667
               }
1668
                        }
1669
                        else
1670
                        {
1671
                            BaroAtUpperLimit = 0;
1672
                                BaroAtLowerLimit = 0;
1673
                        }
1674
                   }
1675
                   else // delay, because of expanding the Baro-Range
1676
                   {
1677
                    // now clear the D-values
1678
                          VarioMeter = 0;
1679
cli();
1680
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
1681
                          if(ACC_AltitudeControl) ACC_AltitudeFusion(1); // init
1682
                          else SummenHoehe = HoehenWert * SM_FILTER;
1683
#else 
1684
              SummenHoehe = HoehenWert * SM_FILTER;
1685
#endif
1686
sei();
1687
                          BaroExpandActive--;
1688
                   }
1689
                // if height control is activated by an rc channel
1690
        if(Parameter_GlobalConfig & CFG_HOEHEN_SCHALTER)  // Regler wird über Schalter gesteuert
1691
                {       // check if parameter is less than activation threshold
1692
                        if(Parameter_HoehenSchalter < 50) // for 3 or 2-state switch height control is disabled in lowest position
1693
                        {   //height control not active
1694
                                if(!delay--)
1695
                                {
1696
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
1697
                                    if(!SpeakHoTT && HoehenReglerAktiv)  SpeakHoTT = SPEAK_ALTITUDE_OFF;
1698
#endif
1699
                                        HoehenReglerAktiv = 0; // disable height control
1700
                                        SollHoehe = HoehenWert;  // update SetPoint with current reading
1701
                                        delay = 1;
1702
                                }
1703
                        }
1704
                        else
1705
                        if(Parameter_HoehenSchalter > 70)
1706
                        {       //height control is activated
1707
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
1708
                            if(!SpeakHoTT && !HoehenReglerAktiv)  SpeakHoTT = SPEAK_ALTITUDE_ON;
1709
#endif
1710
                                delay = 200;
1711
                                HoehenReglerAktiv = 1; // enable height control
1712
                        }
1713
                }
1714
                else // no switchable height control
1715
                {
1716
                        SollHoehe = (/*(int16_t) ExternHoehenValue + */(int16_t) Parameter_HoehenSchalter) * (int)EE_Parameter.Hoehe_Verstaerkung;
1717
                        HoehenReglerAktiv = 1;
1718
                }
1719
                // calculate cos of nick and roll angle used for projection of the vertical hoover gas
1720
                tmp_int  = (int)(IntegralNick/GIER_GRAD_FAKTOR);  // nick angle in deg
1721
                tmp_int2 = (int)(IntegralRoll/GIER_GRAD_FAKTOR);  // roll angle in deg
1722
                tmp_int  = (int16_t)ihypot(tmp_int, tmp_int2); // phytagoras gives effective attitude angle in deg
1723
tmp_int = (tmp_int * Parameter_Hoehe_TiltCompensation) / 100;
1724
                LIMIT_MAX(tmp_int, 60); // limit effective attitude angle
1725
                CosAttitude = c_cos_8192(tmp_int);  // cos of actual attitude
1726
                VarioCharacter = ' ';
1727
                AltitudeSetpointTrimming = 0;
1728
                if(HoehenReglerAktiv && !(FC_StatusFlags & FC_STATUS_EMERGENCY_LANDING))
1729
                {
1730
                // Holger original version
1731
                // start of height control algorithm
1732
                // the height control is only an attenuation of the actual gas stick.
1733
                // I.e. it will work only if the gas stick is higher than the hover gas
1734
                // and the hover height will be allways larger than height setpoint.
1735
                FC_StatusFlags2 |= FC_STATUS2_ALTITUDE_CONTROL;
1736
        if((Parameter_ExtraConfig & CFG2_HEIGHT_LIMIT) || !(Parameter_GlobalConfig & CFG_HOEHEN_SCHALTER))  // Regler wird über Schalter gesteuert)
1737
              {  // old version
1738
                        HCGas = GasMischanteil; // take current stick gas as neutral point for the height control
1739
                        HeightTrimming = 0;
1740
                        AltitudeSetpointTrimming = 0;
1741
                        // set both flags to indicate no vario mode
1742
                        FC_StatusFlags |= (FC_STATUS_VARIO_TRIM_UP|FC_STATUS_VARIO_TRIM_DOWN);
1743
          }
1744
                  else
1745
                  {
1746
                // alternative height control
1747
                // PD-Control with respect to hoover point
1748
                // the thrust loss out of horizontal attitude is compensated
1749
                // the setpoint will be fine adjusted with the gas stick position
1750
                        if(/*1 || */FC_StatusFlags & FC_STATUS_FLY) // trim setpoint only when flying
1751
                        {   // gas stick is above hoover point
1752
                                if(StickGas > (StickGasHover + HEIGHT_CONTROL_STICKTHRESHOLD) && !BaroAtUpperLimit)
1753
                                {
1754
                                        if(FC_StatusFlags & FC_STATUS_VARIO_TRIM_DOWN)
1755
                                        {
1756
                                                FC_StatusFlags &= ~FC_STATUS_VARIO_TRIM_DOWN;
1757
                                                SollHoehe = HoehenWertF; // update setpoint to current heigth
1758
                                        }
1759
                                        // Limit the maximum Altitude
1760
                                        if(Parameter_MaximumAltitude && (SollHoehe/100 > Parameter_MaximumAltitude))
1761
                                         {
1762
                                          AltitudeSetpointTrimming = 0;
1763
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
1764
                                          if(!SpeakHoTT && HoehenWert/95 > Parameter_MaximumAltitude) SpeakHoTT = SPEAK_MAX_ALTITUD;
1765
#endif
1766
                                          VarioCharacter = '=';
1767
                                         }
1768
                                        else
1769
                                        {
1770
                                        if(HeightDeviation > 20) SollHoehe = HoehenWertF; // update setpoint to current heigth 
1771
                                        FC_StatusFlags |= FC_STATUS_VARIO_TRIM_UP;
1772
                                        AltitudeSetpointTrimming = abs(StickGas - (StickGasHover + HEIGHT_CONTROL_STICKTHRESHOLD));
1773
                                        if(LowVoltageLandingActive) AltitudeSetpointTrimming /= 3; // only 33% rising
1774
                                        VarioCharacter = '+';
1775
                                        }
1776
                                        WaypointTrimming = 0;
1777
                                } // gas stick is below hoover point
1778
                                else if(StickGas < (StickGasHover - HEIGHT_CONTROL_STICKTHRESHOLD) && !BaroAtLowerLimit )     // Minus
1779
                                {
1780
                                        if(FC_StatusFlags & FC_STATUS_VARIO_TRIM_UP || (HeightDeviation < -300))
1781
                                        {
1782
                                                FC_StatusFlags &= ~FC_STATUS_VARIO_TRIM_UP;
1783
                                                SollHoehe = HoehenWertF; // update setpoint to current heigth
1784
                                        }
1785
                                        FC_StatusFlags |= FC_STATUS_VARIO_TRIM_DOWN;
1786
                                        AltitudeSetpointTrimming = -abs(StickGas - (StickGasHover - HEIGHT_CONTROL_STICKTHRESHOLD));
1787
                                        VarioCharacter = '-';
1788
                                        WaypointTrimming = 0;
1789
                                }
1790
                                else // Gas Stick in Hover Range
1791
                                {
1792
                                        VarioCharacter = '=';
1793
                    if(FromNC_AltitudeSpeed && FromNC_AltitudeSetpoint > SollHoehe) // von NC gesteuert -> Steigen
1794
                                         {
1795
                                                FC_StatusFlags |= FC_STATUS_VARIO_TRIM_UP;
1796
                                                AltitudeSetpointTrimming = FromNC_AltitudeSpeed;
1797
                                                //HeightTrimming += FromNC_AltitudeSpeed;
1798
                                                WaypointTrimming = 10;
1799
                                                VarioCharacter = '^';
1800
                                                if(FC_StatusFlags & FC_STATUS_VARIO_TRIM_DOWN)  // changed from sinking to rising
1801
                                                {
1802
                                                        FC_StatusFlags &= ~FC_STATUS_VARIO_TRIM_DOWN;
1803
                                                        SollHoehe = HoehenWertF; // update setpoint to current heigth
1804
                                                }
1805
                                         }
1806
                                         else
1807
                    if(FromNC_AltitudeSpeed && FromNC_AltitudeSetpoint < SollHoehe) // von NC gesteuert -> sinken
1808
                                         {
1809
                                                FC_StatusFlags |= FC_STATUS_VARIO_TRIM_DOWN;
1810
                                                AltitudeSetpointTrimming = -FromNC_AltitudeSpeed;
1811
                                                //HeightTrimming -= FromNC_AltitudeSpeed;
1812
                                                WaypointTrimming = -10;
1813
                                                VarioCharacter = 'v';
1814
                                                if(FC_StatusFlags & FC_STATUS_VARIO_TRIM_UP) // changed from rising to sinking
1815
                                                {
1816
                                                        FC_StatusFlags &= ~FC_STATUS_VARIO_TRIM_UP;
1817
                                                        SollHoehe = HoehenWertF; // update setpoint to current heigth
1818
                                                }
1819
                                         }
1820
                                        else
1821
                                        if(FC_StatusFlags & (FC_STATUS_VARIO_TRIM_UP|FC_STATUS_VARIO_TRIM_DOWN))
1822
                                        {
1823
                                                if(!WaypointTrimming) LIMIT_MIN_MAX(SollHoehe, (HoehenWertF-200), (HoehenWertF+200)) // max. 2m Unterschied
1824
                                                else                                    WaypointTrimming = 0;
1825
                                                FC_StatusFlags &= ~(FC_STATUS_VARIO_TRIM_UP|FC_STATUS_VARIO_TRIM_DOWN);
1826
                                                HeightTrimming = 0;
1827
                                                if(Parameter_ExtraConfig & CFG2_VARIO_BEEP) beeptime = 500;
1828
                                                if(!StartTrigger && HoehenWert > 50)
1829
                                                {
1830
                                                 StartTrigger = 1;
1831
                                                }
1832
                                        }
1833
                                }
1834
                                // Trim height set point
1835
                                HeightTrimming += AltitudeSetpointTrimming;
1836
                                if(abs(HeightTrimming) > 500) // bei Waypoint-Flug ist das ca. die 500Hz
1837
                                {
1838
                                        if(WaypointTrimming)
1839
                                         {
1840
                                          if(abs(FromNC_AltitudeSetpoint - SollHoehe) < 10) SollHoehe = FromNC_AltitudeSetpoint;
1841
                                          else SollHoehe += WaypointTrimming;
1842
                                          }
1843
                                        else
1844
                                          {
1845
                                          if(HeightTrimming > 0)        SollHoehe += EE_Parameter.Hoehe_Verstaerkung / 3;
1846
                                          else                    SollHoehe -= EE_Parameter.Hoehe_Verstaerkung / 3;
1847
                                          }
1848
                                        HeightTrimming = 0;
1849
                                        LIMIT_MIN_MAX(HoehenWertF, (HoehenWert-1024), (HoehenWert+1024)); // max. 10m Unterschied
1850
                                        LIMIT_MIN_MAX(SollHoehe, (HoehenWertF-1024), (HoehenWertF+1500)); // max. 15m Unterschied
1851
                                        if(Parameter_ExtraConfig & CFG2_VARIO_BEEP) beeptime = 100;
1852
                                        //update hoover gas stick value when setpoint is shifted
1853
                                        if(FromNC_AltitudeSpeed == 0) CalcStickGasHover();
1854
/*
1855
                       if(!EE_Parameter.Hoehe_StickNeutralPoint && FromNC_AltitudeSpeed == 0)
1856
                       {
1857
                           StickGasHover = HoverGas/STICK_GAIN; //rescale back to stick value
1858
                           StickGasHover = (unsigned int)((unsigned int) StickGasHover * UBat) / BattLowVoltageWarning;
1859
                           if(StickGasHover < 70) StickGasHover = 70;
1860
                           else if(StickGasHover > 175) StickGasHover = 175;
1861
                       }
1862
*/
1863
                                }
1864
              if(BaroExpandActive) SollHoehe = HoehenWertF; // update setpoint to current altitude if Expanding is active
1865
                        } //if FCFlags & MKFCFLAG_FLY
1866
                        else
1867
                        {
1868
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
1869
                         ACC_AltitudeFusion(1); // init the ACC and Altitude fusion
1870
#endif
1871
                         SollHoehe = HoehenWertF - 2000;
1872
 
1873
                         if(EE_Parameter.Hoehe_StickNeutralPoint) StickGasHover = EE_Parameter.Hoehe_StickNeutralPoint;
1874
                         else StickGasHover = 127;
1875
                         HoverGas = GasMischanteil;
1876
                         VarioCharacter = '.';
1877
                         }
1878
                        HCGas = HoverGas;      // take hover gas (neutral point)
1879
                   }
1880
         if(HoehenWertF > SollHoehe || !(Parameter_ExtraConfig & CFG2_HEIGHT_LIMIT))
1881
                 {
1882
                  if(!ACC_AltitudeControl)
1883
                  {
1884
                        // from this point the Heigth Control Algorithm is identical for both versions
1885
                        if(BaroExpandActive) // baro range expanding active
1886
                        {
1887
                                HCGas = HoverGas; // hover while expanding baro adc range
1888
                                HeightDeviation = 0;
1889
                        } // EOF // baro range expanding active
1890
                        else // valid data from air pressure sensor
1891
                        {
1892
                                // ------------------------- P-Part ----------------------------
1893
                                tmp_long = (HoehenWertF - SollHoehe); // positive when too high
1894
                                LIMIT_MIN_MAX(tmp_long, -32767L, 32767L);       // avoid overflov when casting to int16_t
1895
                                HeightDeviation = (int)(tmp_long); // positive when too high
1896
                                tmp_long = (tmp_long * (long)Parameter_Hoehe_P) / 32L; // p-part
1897
                                LIMIT_MIN_MAX(tmp_long, -127 * STICK_GAIN, 256 * STICK_GAIN); // more than the full range makes no sense
1898
                                GasReduction = tmp_long;
1899
                                // ------------------------- D-Part 1: Vario Meter ----------------------------
1900
                                tmp_int = VarioMeter / 8;
1901
                                LIMIT_MIN_MAX(tmp_int, -127, 128);
1902
                                tmp_int = (tmp_int * (long)Parameter_Luftdruck_D) / 4L; // scale to d-gain parameter
1903
                                LIMIT_MIN_MAX(tmp_int,-64 * STICK_GAIN, 64 * STICK_GAIN);
1904
                                if(FC_StatusFlags & (FC_STATUS_VARIO_TRIM_UP|FC_STATUS_VARIO_TRIM_DOWN)) tmp_int /= 4; // reduce d-part while trimming setpoint
1905
                                else
1906
                                if(Parameter_ExtraConfig & CFG2_HEIGHT_LIMIT) tmp_int /= 8; // reduce d-part in "Deckel" mode
1907
                                GasReduction += tmp_int;
1908
                        } // EOF no baro range expanding
1909
                        // ------------------------ D-Part 2: ACC-Z Integral  ------------------------
1910
            if(Parameter_Hoehe_ACC_Wirkung)
1911
                         {
1912
                          tmp_long = ((Mess_Integral_Hoch / 128L) * (int32_t) Parameter_Hoehe_ACC_Wirkung) / (128L / STICK_GAIN);
1913
                          LIMIT_MIN_MAX(tmp_long, -32 * STICK_GAIN, 64 * STICK_GAIN);
1914
                          GasReduction += tmp_long;
1915
                         }
1916
/*                      // ------------------------ D-Part 3: GpsZ  ----------------------------------
1917
                        tmp_int = (Parameter_Hoehe_GPS_Z * (int)FromNaviCtrl_Value.GpsZ)/128L;
1918
            LIMIT_MIN_MAX(tmp_int, -32 * STICK_GAIN, 64 * STICK_GAIN);
1919
                        GasReduction += tmp_int;
1920
*/
1921
            GasReduction = (long)((long)GasReduction * HoverGas) / 512; // scale to the gas value
1922
 
1923
                        // ------------------------                  ----------------------------------
1924
                        HCGas -= GasReduction;
1925
                        // limit deviation from hoover point within the target region
1926
                        if(!AltitudeSetpointTrimming && HoverGas > 0) // height setpoint is not changed and hoover gas not zero
1927
                        {
1928
                         unsigned int tmp;
1929
                         tmp = abs(HeightDeviation);
1930
                         if(tmp <= 60)
1931
                         {
1932
                          LIMIT_MIN_MAX(HCGas, HoverGasMin, HoverGasMax); // limit gas around the hoover point
1933
                         }
1934
                         else
1935
                         {
1936
                                tmp = (tmp - 60) / 32;
1937
                                if(tmp > 15) tmp = 15;
1938
                           if(HeightDeviation > 0)
1939
                                {
1940
                                tmp = (HoverGasMin * (16 - tmp)) / 16;
1941
                                LIMIT_MIN_MAX(HCGas, tmp, HoverGasMax); // limit gas around the hoover point
1942
                                }
1943
                                else
1944
                                {
1945
                                tmp = (HoverGasMax * (tmp + 16)) / 16;
1946
                                LIMIT_MIN_MAX(HCGas, HoverGasMin, tmp); // limit gas around the hoover point
1947
                                }
1948
                          }
1949
                        }
1950
                        // strech control output by inverse attitude projection 1/cos
1951
            // + 1/cos(angle)  ++++++++++++++++++++++++++
1952
                        tmp_long2 = (int32_t)HCGas;
1953
                        tmp_long2 *= 8192L;
1954
                        tmp_long2 /= CosAttitude;
1955
                        HCGas = (int16_t)tmp_long2;
1956
                        // update height control gas averaging
1957
                        FilterHCGas = (FilterHCGas * (HC_GAS_AVERAGE - 1) + HCGas) / HC_GAS_AVERAGE;
1958
                        // limit height control gas pd-control output
1959
                        LIMIT_MIN_MAX(FilterHCGas, EE_Parameter.Hoehe_MinGas * STICK_GAIN, (MAX_GAS - 20) * STICK_GAIN);
1960
                        // set GasMischanteil to HeightControlGasFilter
1961
            if(Parameter_ExtraConfig & CFG2_HEIGHT_LIMIT)
1962
                        {  // old version
1963
                                LIMIT_MAX(FilterHCGas, GasMischanteil); // nicht mehr als Gas
1964
                                GasMischanteil = FilterHCGas;
1965
                        }
1966
                        else GasMischanteil = FilterHCGas + (GasMischanteil - HoverGas) / 4; // only in Vario-Mode
1967
                   }
1968
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
1969
          else // ACC-Altitude control
1970
                   {
1971
                        // from this point the Heigth Control Algorithm is identical for both versions
1972
                        if(BaroExpandActive) // baro range expanding active
1973
                        {
1974
                                HCGas = HoverGas; // hover while expanding baro adc range
1975
                                HeightDeviation = 0;
1976
                        } // EOF // baro range expanding active
1977
                        else // valid data from air pressure sensor
1978
                        {
1979
                                // ------------------------- P-Part ----------------------------
1980
                                tmp_long = (HoehenWertF - SollHoehe); // positive when too high
1981
                                LIMIT_MIN_MAX(tmp_long, -32767L, 32767L);       // avoid overflov when casting to int16_t
1982
                                HeightDeviation = (int)(tmp_long); // positive when too high
1983
                                tmp_long = (tmp_long * (long)Parameter_Hoehe_P) / 32L; // p-part
1984
                                LIMIT_MIN_MAX(tmp_long, -511 * STICK_GAIN, 512 * STICK_GAIN); // more than full range makes sense
1985
                                GasReduction = tmp_long;
1986
                                // ------------------------ D-Part: ACC-Z Integral  ------------------------
1987
                                tmp_long = VarioMeter + (AdWertAccHoch * Parameter_Hoehe_ACC_Wirkung)/256;
1988
                                // ------------------------- D-Part: Vario Meter ----------------------------
1989
                                if(WaypointTrimming) {
1990
                                        Variance = AltitudeSetpointTrimming * 8;       
1991
                                } else {
1992
                                        Variance = AltitudeSetpointTrimming * EE_Parameter.Hoehe_Verstaerkung*9/32;
1993
                                }
1994
                                tmp_long -= (long)Variance;
1995
                                tmp_long = (tmp_long * (long)Parameter_Luftdruck_D) / 32; // scale to d-gain parameter
1996
                                LIMIT_MIN_MAX(tmp_long,-511 * STICK_GAIN, 512 * STICK_GAIN);
1997
                                GasReduction += tmp_long;
1998
                        } // EOF no baro range expanding
1999
                        HCGas -= GasReduction;
2000
                        LIMIT_MIN_MAX(HCGas, HoverGasMin, HoverGasMax); // limits gas around hover point
2001
                        // strech control output by inverse attitude projection 1/cos
2002
            // + 1/cos(angle)  ++++++++++++++++++++++++++
2003
                        tmp_long2 = (int32_t)HCGas;
2004
                        tmp_long2 *= 8192L;
2005
                        tmp_long2 /= CosAttitude;
2006
                        HCGas = (int16_t)tmp_long2;
2007
                        // update height control gas averaging
2008
                        FilterHCGas = (FilterHCGas * (HC_GAS_AVERAGE - 1) + HCGas) / HC_GAS_AVERAGE;
2009
                        // limit height control gas pd-control output
2010
                        int min;
2011
                        if(GasIsZeroCnt > 400 || (FC_StatusFlags2 & FC_STATUS2_WAIT_FOR_TAKEOFF)) min = EE_Parameter.Gas_Min; else min = EE_Parameter.Hoehe_MinGas;
2012
                        LIMIT_MIN_MAX(FilterHCGas, min * STICK_GAIN, (MAX_GAS - 20) * STICK_GAIN)
2013
                        // set GasMischanteil to HeightControlGasFilter
2014
            if(Parameter_ExtraConfig & CFG2_HEIGHT_LIMIT)
2015
                        {  // old version
2016
                                LIMIT_MAX(FilterHCGas, GasMischanteil); // nicht mehr als Gas
2017
                                GasMischanteil = FilterHCGas;
2018
                        }
2019
                        else GasMischanteil = FilterHCGas;
2020
           } // end of ACC-Altitude control
2021
#endif
2022
                  }
2023
                }// EOF height control active
2024
                else // HC not active
2025
                {
2026
                        //update hoover gas stick value when HC is not active
2027
                        CalcStickGasHover();
2028
/*                      if(!EE_Parameter.Hoehe_StickNeutralPoint)
2029
                        {
2030
                                StickGasHover = HoverGas/STICK_GAIN; // rescale back to stick value
2031
                                StickGasHover = (unsigned int)((unsigned int) StickGasHover * UBat) / BattLowVoltageWarning;
2032
                        }
2033
                        else StickGasHover = EE_Parameter.Hoehe_StickNeutralPoint;
2034
            LIMIT_MIN_MAX(StickGasHover, 70, 175); // reserve some range for trim up and down
2035
*/             
2036
                        FilterHCGas = GasMischanteil;
2037
                        // set both flags to indicate no vario mode
2038
                        FC_StatusFlags |= (FC_STATUS_VARIO_TRIM_UP|FC_STATUS_VARIO_TRIM_DOWN);
2039
                        FC_StatusFlags2 &= ~FC_STATUS2_ALTITUDE_CONTROL;
2040
                }
2041
                // Hover gas estimation by averaging gas control output on small z-velocities
2042
                // this is done only if height contol option is selected in global config and aircraft is flying
2043
                if((FC_StatusFlags & FC_STATUS_FLY))// && !(FC_SatusFlags & FC_STATUS_EMERGENCY_LANDING))
2044
                {
2045
                        //if(HoverGasFilter == 0 || StartTrigger == 1)  HoverGasFilter = HOVER_GAS_AVERAGE * (unsigned long)(GasMischanteil); // init estimation
2046
                        if(HoverGasFilter == 0 || StartTrigger == 1)  HoverGasFilter = HOVER_GAS_AVERAGE * (unsigned long)(HoverGas); // 0.90f: geändert
2047
                        if(StartTrigger == 1) StartTrigger = 2;
2048
                                tmp_long2 = (int32_t)GasMischanteil; // take current thrust
2049
                                tmp_long2 *= CosAttitude;            // apply attitude projection
2050
                                tmp_long2 /= 8192;
2051
                                // average vertical projected thrust
2052
                            if(modell_fliegt < 4000) // the first 8 seconds
2053
                                {   // reduce the time constant of averaging by factor of 4 to get much faster a stable value
2054
                                        HoverGasFilter -= HoverGasFilter/(HOVER_GAS_AVERAGE/16L);
2055
                                        HoverGasFilter += 16L * tmp_long2;
2056
                                }
2057
                if(modell_fliegt < 8000) // the first 16 seconds
2058
                                {   // reduce the time constant of averaging by factor of 2 to get much faster a stable value
2059
                                        HoverGasFilter -= HoverGasFilter/(HOVER_GAS_AVERAGE/4L);
2060
                                        HoverGasFilter += 4L * tmp_long2;
2061
                                }
2062
                          else //later
2063
                          if(abs(VarioMeter) < 100 && abs(HoehenWertF - SollHoehe) < 256) // only on small vertical speed & difference is small (only descending)
2064
                                {
2065
                                        HoverGasFilter -= HoverGasFilter/HOVER_GAS_AVERAGE;
2066
                                        HoverGasFilter += tmp_long2;
2067
                                }
2068
                                HoverGas = (int16_t)(HoverGasFilter/HOVER_GAS_AVERAGE);
2069
                                if(EE_Parameter.Hoehe_HoverBand)
2070
                                {
2071
                                        int16_t band;
2072
                                        band = HoverGas / EE_Parameter.Hoehe_HoverBand; // the higher the parameter the smaller the range
2073
                                        HoverGasMin = HoverGas - band;
2074
                                        HoverGasMax = HoverGas + band;
2075
                                }
2076
                                else
2077
                                {       // no limit
2078
                                        HoverGasMin = 0;
2079
                                        HoverGasMax = 1023;
2080
                                }
2081
                }
2082
                 else
2083
                  {
2084
                   StartTrigger = 0;
2085
                   HoverGasFilter = 0;
2086
                   HoverGas = 0;
2087
                  }
2088
        }// EOF Parameter_GlobalConfig & CFG_HEIGHT_CONTROL
2089
        else
2090
        {
2091
                // set undefined state to indicate vario off
2092
                FC_StatusFlags |= (FC_STATUS_VARIO_TRIM_UP|FC_STATUS_VARIO_TRIM_DOWN);
2093
        } // EOF no height control
2094
 
2095
   // Limits the maximum gas in case of "Out of Range emergency landing"
2096
   if(NC_To_FC_Flags & NC_TO_FC_EMERGENCY_LANDING)
2097
        {
2098
         if(GasMischanteil/STICK_GAIN > HooverGasEmergencyPercent && HoverGas) GasMischanteil = HooverGasEmergencyPercent * STICK_GAIN;
2099
         SollHoehe = HoehenWertF; // update setpoint to current heigth
2100
          beeptime = 15000;
2101
          BeepMuster = 0x0E00;
2102
        }
2103
    // limit gas to parameter setting
2104
  LIMIT_MIN(GasMischanteil, (MIN_GAS + 10) * STICK_GAIN);
2105
  if(GasMischanteil > (MAX_GAS - 20) * STICK_GAIN) GasMischanteil = (MAX_GAS - 20) * STICK_GAIN;
2106
 
2107
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2108
// all BL-Ctrl connected?
2109
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2110
#ifndef REDUNDANT_FC_SLAVE
2111
  if(MissingMotor || Capacity.MinOfMaxPWM < 254 || NC_ErrorCode)      // wait until all BL-Ctrls started and no Errors
2112
  if(modell_fliegt > 1 && modell_fliegt < 50 && GasMischanteil > 0)    // only during start-phase
2113
   {
2114
    modell_fliegt = 1;
2115
        GasMischanteil = (MIN_GAS + 10) * STICK_GAIN;
2116
#if (defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__))
2117
        if(Capacity.MinOfMaxPWM < 40) SpeakHoTT = SPEAK_ERR_MOTOR;
2118
#endif
2119
   }
2120
#endif
2121
 
2122
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2123
// send SPI pending bytes
2124
 if(BytegapSPI == 0)  SPI_TransmitByte();
2125
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2126
// + Mischer und PI-Regler
2127
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2128
  DebugOut.Analog[7] = GasMischanteil;  // achtung: Muss auf [7] bleiben wegen SPI.C
2129
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2130
// Gier-Anteil
2131
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2132
    GierMischanteil = MesswertGier - sollGier * STICK_GAIN;     // Regler für Gier
2133
#define MIN_GIERGAS  (40*STICK_GAIN)  // unter diesem Gaswert trotzdem Gieren
2134
   if(GasMischanteil > MIN_GIERGAS)
2135
    {
2136
     if(GierMischanteil > (GasMischanteil / 2)) GierMischanteil = GasMischanteil / 2;
2137
     if(GierMischanteil < -(GasMischanteil / 2)) GierMischanteil = -(GasMischanteil / 2);
2138
    }
2139
    else
2140
    {
2141
     if(GierMischanteil > (MIN_GIERGAS / 2))  GierMischanteil = MIN_GIERGAS / 2;
2142
     if(GierMischanteil < -(MIN_GIERGAS / 2)) GierMischanteil = -(MIN_GIERGAS / 2);
2143
    }
2144
    tmp_int = MAX_GAS*STICK_GAIN;
2145
    if(GierMischanteil > ((tmp_int - GasMischanteil))) GierMischanteil = ((tmp_int - GasMischanteil));
2146
    if(GierMischanteil < -((tmp_int - GasMischanteil))) GierMischanteil = -((tmp_int - GasMischanteil));
2147
 
2148
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2149
// Nick-Achse
2150
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2151
    DiffNick = MesswertNick - StickNick;        // Differenz bestimmen
2152
    if(IntegralFaktor) SummeNick += IntegralNickMalFaktor - StickNick; // I-Anteil bei Winkelregelung
2153
    else  SummeNick += DiffNick; // I-Anteil bei HH
2154
    if(SummeNick >  (STICK_GAIN * 16000L)) SummeNick =  (STICK_GAIN * 16000L);
2155
    if(SummeNick < -(16000L * STICK_GAIN)) SummeNick = -(16000L * STICK_GAIN);
2156
 
2157
    if(EE_Parameter.Gyro_Stability <= 8)        pd_ergebnis_nick = (EE_Parameter.Gyro_Stability * DiffNick) / 8; // PI-Regler für Nick
2158
    else                                                                        pd_ergebnis_nick = ((EE_Parameter.Gyro_Stability / 2) * DiffNick) / 4; // Überlauf verhindern
2159
    pd_ergebnis_nick +=  SummeNick / Ki;
2160
 
2161
    tmp_int = (long)((long)Parameter_DynamicStability * (long)(GasMischanteil + abs(GierMischanteil)/2)) / 64;
2162
    if(pd_ergebnis_nick >  tmp_int) pd_ergebnis_nick =  tmp_int;
2163
    if(pd_ergebnis_nick < -tmp_int) pd_ergebnis_nick = -tmp_int;
2164
 
2165
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2166
// Roll-Achse
2167
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2168
        DiffRoll = MesswertRoll - StickRoll;    // Differenz bestimmen
2169
    if(IntegralFaktor) SummeRoll += IntegralRollMalFaktor - StickRoll;// I-Anteil bei Winkelregelung
2170
    else                 SummeRoll += DiffRoll;  // I-Anteil bei HH
2171
    if(SummeRoll >  (STICK_GAIN * 16000L)) SummeRoll =  (STICK_GAIN * 16000L);
2172
    if(SummeRoll < -(16000L * STICK_GAIN)) SummeRoll = -(16000L * STICK_GAIN);
2173
 
2174
    if(EE_Parameter.Gyro_Stability <= 8)        pd_ergebnis_roll = (EE_Parameter.Gyro_Stability * DiffRoll) / 8;        // PI-Regler für Roll
2175
        else                                                                    pd_ergebnis_roll = ((EE_Parameter.Gyro_Stability / 2) * DiffRoll) / 4;  // Überlauf verhindern
2176
    pd_ergebnis_roll += SummeRoll / Ki;
2177
 
2178
    tmp_int = (long)((long)Parameter_DynamicStability * (long)(GasMischanteil + abs(GierMischanteil)/2)) / 64;
2179
    if(pd_ergebnis_roll >  tmp_int) pd_ergebnis_roll =  tmp_int;
2180
    if(pd_ergebnis_roll < -tmp_int) pd_ergebnis_roll = -tmp_int;
2181
 
2182
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2183
// send SPI pending bytes
2184
        if(BytegapSPI == 0)  SPI_TransmitByte();
2185
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2186
// Universal Mixer
2187
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2188
        for(i=0; i<MAX_MOTORS; i++)
2189
        {
2190
                signed int tmp_int;
2191
                if(Mixer.Motor[i][0] > 0)
2192
                {
2193
                        // Gas
2194
                        if(Mixer.Motor[i][0] == 64) tmp_int = GasMischanteil; else tmp_int =  ((long)GasMischanteil * Mixer.Motor[i][0]) / 64L;
2195
                        // Nick
2196
                        if(Mixer.Motor[i][1] == 64) tmp_int += pd_ergebnis_nick;
2197
                        else if(Mixer.Motor[i][1] == -64) tmp_int -= pd_ergebnis_nick;
2198
                        else tmp_int += ((long)pd_ergebnis_nick * Mixer.Motor[i][1]) / 64L;
2199
            // Roll
2200
                        if(Mixer.Motor[i][2] == 64) tmp_int += pd_ergebnis_roll;
2201
                        else if(Mixer.Motor[i][2] == -64) tmp_int -= pd_ergebnis_roll;
2202
                        else tmp_int += ((long)pd_ergebnis_roll * Mixer.Motor[i][2]) / 64L;
2203
            // Gier
2204
                        if(Mixer.Motor[i][3] == 64) tmp_int += GierMischanteil;
2205
                        else if(Mixer.Motor[i][3] == -64) tmp_int -= GierMischanteil;
2206
                        else tmp_int += ((long)GierMischanteil * Mixer.Motor[i][3]) / 64L;
2207
#ifdef REDUNDANT_FC_SLAVE
2208
                        tmp_int = (tmp_motorwert[i] + tmp_int) / 2;    
2209
#else
2210
                        if(Motor[i].Version & MOTOR_STATE_FAST_MODE || tmp_int > tmp_motorwert[i]) tmp_int = (tmp_motorwert[i] + tmp_int) / 2;      // Beschleunigen
2211
            else
2212
                         {  // BL-Ctrl 1.0 or 2.0 
2213
                            if(EE_Parameter.MotorSmooth == 0)
2214
                                {
2215
                                  tmp_int = 2 * tmp_int - tmp_motorwert[i];  // original MotorSmoothing
2216
                                }
2217
                                                        else  // 1 means tmp_int = tmp_int;
2218
                            if(EE_Parameter.MotorSmooth > 1)
2219
                                {
2220
                                  // If >= 2 then allow >= 50% of the intended step down to rapidly reach the intended value.
2221
                                  tmp_int = tmp_int + ((tmp_motorwert[i] - tmp_int) / EE_Parameter.MotorSmooth);
2222
                                }
2223
                        }
2224
#endif
2225
                        LIMIT_MIN_MAX(tmp_int,(int) MIN_GAS * 4,(int) MAX_GAS * 4);
2226
                        Motor[i].SetPoint = tmp_int / 4;
2227
                        Motor[i].SetPointLowerBits = (tmp_int % 4)<<1; // (3 bits total)
2228
            tmp_motorwert[i] = tmp_int;
2229
                }
2230
                else
2231
                {
2232
                        Motor[i].SetPoint = 0;
2233
                        Motor[i].SetPointLowerBits = 0;
2234
                }
2235
        }
2236
#if (defined(REDUNDANT_FC_MASTER) || defined(REDUNDANT_FC_SLAVE))
2237
if(Parameter_UserParam6 > 230)  // Motor1-Test
2238
 {
2239
  Motor[0].SetPoint = 0;
2240
  FC_StatusFlags3 |= FC_STATUS3_REDUNDANCE_TEST;
2241
 }
2242
 else
2243
 if(Parameter_UserParam7 <= 150) // I2C-Test
2244
 {
2245
  FC_StatusFlags3 &= ~FC_STATUS3_REDUNDANCE_TEST;
2246
 }
2247
#endif
2248
}
2249
//DebugOut.Analog[16]