Subversion Repositories FlightCtrl

Rev

Rev 1775 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1612 dongfang 1
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2
// + Copyright (c) 04.2007 Holger Buss
3
// + Nur für den privaten Gebrauch
4
// + www.MikroKopter.com
5
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6
// + Es gilt für das gesamte Projekt (Hardware, Software, Binärfiles, Sourcecode und Dokumentation),
7
// + dass eine Nutzung (auch auszugsweise) nur für den privaten (nicht-kommerziellen) Gebrauch zulässig ist.
8
// + Sollten direkte oder indirekte kommerzielle Absichten verfolgt werden, ist mit uns (info@mikrokopter.de) Kontakt
9
// + bzgl. der Nutzungsbedingungen aufzunehmen.
10
// + Eine kommerzielle Nutzung ist z.B.Verkauf von MikroKoptern, Bestückung und Verkauf von Platinen oder Bausätzen,
11
// + Verkauf von Luftbildaufnahmen, usw.
12
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
13
// + Werden Teile des Quellcodes (mit oder ohne Modifikation) weiterverwendet oder veröffentlicht,
14
// + unterliegen sie auch diesen Nutzungsbedingungen und diese Nutzungsbedingungen incl. Copyright müssen dann beiliegen
15
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
16
// + Sollte die Software (auch auszugesweise) oder sonstige Informationen des MikroKopter-Projekts
17
// + auf anderen Webseiten oder sonstigen Medien veröffentlicht werden, muss unsere Webseite "http://www.mikrokopter.de"
18
// + eindeutig als Ursprung verlinkt werden
19
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
20
// + Keine Gewähr auf Fehlerfreiheit, Vollständigkeit oder Funktion
21
// + Benutzung auf eigene Gefahr
22
// + Wir übernehmen keinerlei Haftung für direkte oder indirekte Personen- oder Sachschäden
23
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
24
// + Die Portierung der Software (oder Teile davon) auf andere Systeme (ausser der Hardware von www.mikrokopter.de) ist nur
25
// + mit unserer Zustimmung zulässig
26
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
27
// + Die Funktion printf_P() unterliegt ihrer eigenen Lizenz und ist hiervon nicht betroffen
28
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
29
// + Redistributions of source code (with or without modifications) must retain the above copyright notice,
30
// + this list of conditions and the following disclaimer.
31
// +   * Neither the name of the copyright holders nor the names of contributors may be used to endorse or promote products derived
32
// +     from this software without specific prior written permission.
33
// +   * The use of this project (hardware, software, binary files, sources and documentation) is only permittet
34
// +     for non-commercial use (directly or indirectly)
35
// +     Commercial use (for excample: selling of MikroKopters, selling of PCBs, assembly, ...) is only permitted
36
// +     with our written permission
37
// +   * If sources or documentations are redistributet on other webpages, out webpage (http://www.MikroKopter.de) must be
38
// +     clearly linked as origin
39
// +   * porting to systems other than hardware from www.mikrokopter.de is not allowed
40
// +  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
41
// +  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42
// +  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43
// +  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
44
// +  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
45
// +  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
46
// +  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
47
// +  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN// +  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
48
// +  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
49
// +  POSSIBILITY OF SUCH DAMAGE.
50
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
51
#include <inttypes.h>
52
#include <stdlib.h>
1775 - 53
//#include "mymath.h"
1612 dongfang 54
#include "timer0.h"
55
#include "uart0.h"
56
#include "rc.h"
57
#include "eeprom.h"
58
 
59
typedef enum
60
  {
61
    GPS_FLIGHT_MODE_UNDEF,
62
    GPS_FLIGHT_MODE_FREE,
63
    GPS_FLIGHT_MODE_AID,
64
    GPS_FLIGHT_MODE_HOME,
65
  } FlightMode_t;
66
 
67
#define GPS_POSINTEGRAL_LIMIT 32000
68
#define GPS_STICK_LIMIT         45              // limit of gps stick control to avoid critical flight attitudes
69
#define GPS_P_LIMIT                     25
70
 
71
 
72
typedef struct
73
{
74
  int32_t Longitude;
75
  int32_t Latitude;
76
  int32_t Altitude;
77
  Status_t Status;
78
} GPS_Pos_t;
79
 
80
// GPS coordinates for hold position
81
GPS_Pos_t HoldPosition  = {0,0,0,INVALID};
82
// GPS coordinates for home position
83
GPS_Pos_t HomePosition  = {0,0,0,INVALID};
84
// the current flight mode
85
FlightMode_t FlightMode = GPS_FLIGHT_MODE_UNDEF;
86
 
87
 
88
// ---------------------------------------------------------------------------------
1775 - 89
void GPS_UpdateParameter(void) {
1612 dongfang 90
  static FlightMode_t FlightModeOld = GPS_FLIGHT_MODE_UNDEF;
1775 - 91
 
92
  if((RC_Quality < 100) || (MKFlags & MKFLAG_EMERGENCY_LANDING)) {
93
    FlightMode = GPS_FLIGHT_MODE_FREE;
94
  } else {
95
    if     (dynamicParams.NaviGpsModeControl <  50) FlightMode = GPS_FLIGHT_MODE_AID;
96
    else if(dynamicParams.NaviGpsModeControl < 180) FlightMode = GPS_FLIGHT_MODE_FREE;
97
    else                                          FlightMode = GPS_FLIGHT_MODE_HOME;
98
  }
1612 dongfang 99
 
1775 - 100
  if (FlightMode != FlightModeOld) {
101
    BeepTime = 100;
102
  }
1612 dongfang 103
  FlightModeOld = FlightMode;
104
}
105
 
106
// ---------------------------------------------------------------------------------
107
// This function defines a good GPS signal condition
1775 - 108
uint8_t GPS_IsSignalOK(void) {
1612 dongfang 109
  static uint8_t GPSFix = 0;
1775 - 110
  if( (GPSInfo.status != INVALID)  && (GPSInfo.satfix == SATFIX_3D) && (GPSInfo.flags & FLAG_GPSFIXOK) && ((GPSInfo.satnum >= staticParams.NaviGpsMinSat) || GPSFix)) {
111
    GPSFix = 1;
112
    return 1;
113
  }
1612 dongfang 114
  else return (0);
1775 - 115
}
1612 dongfang 116
 
117
// ---------------------------------------------------------------------------------
118
// rescale xy-vector length to  limit
1775 - 119
uint8_t GPS_LimitXY(int32_t *x, int32_t *y, int32_t limit) {
1612 dongfang 120
  uint8_t retval = 0;
121
  int32_t len;
122
  len = (int32_t)c_sqrt(*x * *x + *y * *y);
1775 - 123
  if (len > limit) {
124
    // normalize control vector components to the limit
125
    *x  = (*x  * limit) / len;
126
    *y  = (*y  * limit) / len;
127
    retval = 1;
128
  }
1612 dongfang 129
  return(retval);
130
}
131
 
132
// checks nick and roll sticks for manual control
1775 - 133
uint8_t GPS_IsManualControlled(void) {
134
  if ((abs(PPM_in[staticParams.ChannelAssignment[CH_NICK]]) < staticParams.NaviStickThreshold) && (abs(PPM_in[staticParams.ChannelAssignment[CH_ROLL]]) < staticParams.NaviStickThreshold)) return 0;
1612 dongfang 135
  else return 1;
136
}
137
 
138
// set given position to current gps position
1775 - 139
uint8_t GPS_SetCurrPosition(GPS_Pos_t * pGPSPos) {
1612 dongfang 140
  uint8_t retval = 0;
141
  if(pGPSPos == NULL) return(retval);   // bad pointer
142
 
1775 - 143
  if(GPS_IsSignalOK()) {        // is GPS signal condition is fine
144
    pGPSPos->Longitude  = GPSInfo.longitude;
145
    pGPSPos->Latitude   = GPSInfo.latitude;
146
    pGPSPos->Altitude   = GPSInfo.altitude;
147
    pGPSPos->Status     = NEWDATA;
148
    retval = 1;
149
  } else {      // bad GPS signal condition
150
    pGPSPos->Status = INVALID;
151
    retval = 0;
152
  }
1612 dongfang 153
  return(retval);
154
}
155
 
156
// clear position
1775 - 157
uint8_t GPS_ClearPosition(GPS_Pos_t * pGPSPos) {
1612 dongfang 158
  uint8_t retval = 0;
1775 - 159
  if(pGPSPos == NULL)
160
    return retval;      // bad pointer
161
  else {
162
    pGPSPos->Longitude  = 0;
163
    pGPSPos->Latitude   = 0;
164
    pGPSPos->Altitude   = 0;
165
    pGPSPos->Status     = INVALID;
166
    retval = 1;
167
  }
1612 dongfang 168
  return (retval);
169
}
170
 
171
// disable GPS control sticks
1775 - 172
void GPS_Neutral(void) {
1612 dongfang 173
  GPSStickNick = 0;
174
  GPSStickRoll = 0;
175
}
176
 
177
// calculates the GPS control stick values from the deviation to target position
178
// if the pointer to the target positin is NULL or is the target position invalid
179
// then the P part of the controller is deactivated.
1775 - 180
void GPS_PIDController(GPS_Pos_t *pTargetPos) {
1612 dongfang 181
  static int32_t PID_Nick, PID_Roll;
182
  int32_t coscompass, sincompass;
183
  int32_t GPSPosDev_North, GPSPosDev_East; // Position deviation in cm
184
  int32_t P_North = 0, D_North = 0, P_East = 0, D_East = 0, I_North = 0, I_East = 0;
185
  int32_t PID_North = 0, PID_East = 0;
186
  static int32_t cos_target_latitude = 1;
187
  static int32_t GPSPosDevIntegral_North = 0, GPSPosDevIntegral_East = 0;
188
  static GPS_Pos_t *pLastTargetPos = 0;
189
 
190
  // if GPS data and Compass are ok
1775 - 191
  if( GPS_IsSignalOK() && (CompassHeading >= 0)) {
192
    if(pTargetPos != NULL) // if there is a target position
193
      {
194
        if(pTargetPos->Status != INVALID) // and the position data are valid
195
          {
196
            // if the target data are updated or the target pointer has changed
197
            if ((pTargetPos->Status != PROCESSED) || (pTargetPos != pLastTargetPos) )
198
              {
199
                // reset error integral
200
                GPSPosDevIntegral_North = 0;
201
                GPSPosDevIntegral_East = 0;
202
                // recalculate latitude projection
203
                cos_target_latitude = (int32_t)c_cos_8192((int16_t)(pTargetPos->Latitude/10000000L));
204
                // remember last target pointer
205
                pLastTargetPos = pTargetPos;
206
                // mark data as processed
207
                pTargetPos->Status = PROCESSED;
208
              }
209
            // calculate position deviation from latitude and longitude differences
210
            GPSPosDev_North = (GPSInfo.latitude - pTargetPos->Latitude); // to calculate real cm we would need *111/100 additionally
211
            GPSPosDev_East  = (GPSInfo.longitude - pTargetPos->Longitude); // to calculate real cm we would need *111/100 additionally
212
            // calculate latitude projection
213
            GPSPosDev_East  *= cos_target_latitude;
214
            GPSPosDev_East /= 8192;
215
          }
216
        else // no valid target position available
217
          {
218
            // reset error
219
            GPSPosDev_North = 0;
220
            GPSPosDev_East = 0;
221
            // reset error integral
222
            GPSPosDevIntegral_North = 0;
223
            GPSPosDevIntegral_East = 0;
224
          }
225
      }
226
    else // no target position available
227
      {
228
        // reset error
229
        GPSPosDev_North = 0;
230
        GPSPosDev_East = 0;
231
        // reset error integral
232
        GPSPosDevIntegral_North = 0;
233
        GPSPosDevIntegral_East = 0;
234
      }
235
 
236
    //Calculate PID-components of the controller
237
 
238
    // D-Part
239
    D_North = ((int32_t)dynamicParams.NaviGpsD * GPSInfo.velnorth)/512;
240
    D_East =  ((int32_t)dynamicParams.NaviGpsD * GPSInfo.veleast)/512;
241
 
242
    // P-Part
243
    P_North = ((int32_t)dynamicParams.NaviGpsP * GPSPosDev_North)/2048;
244
    P_East =  ((int32_t)dynamicParams.NaviGpsP * GPSPosDev_East)/2048;
245
 
246
    // I-Part
247
    I_North = ((int32_t)dynamicParams.NaviGpsI * GPSPosDevIntegral_North)/8192;
248
    I_East =  ((int32_t)dynamicParams.NaviGpsI * GPSPosDevIntegral_East)/8192;
249
 
250
    // combine P & I
251
    PID_North = P_North + I_North;
252
    PID_East  = P_East  + I_East;
253
    if(!GPS_LimitXY(&PID_North, &PID_East, GPS_P_LIMIT))
254
      {
255
        GPSPosDevIntegral_North += GPSPosDev_North/16;
256
        GPSPosDevIntegral_East  += GPSPosDev_East/16;
257
        GPS_LimitXY(&GPSPosDevIntegral_North, &GPSPosDevIntegral_East, GPS_POSINTEGRAL_LIMIT);
258
      }
259
 
260
    // combine PI- and D-Part
261
    PID_North += D_North;
262
    PID_East  += D_East;
263
 
264
    // scale combination with gain.
265
    PID_North = (PID_North * (int32_t)dynamicParams.NaviGpsGain) / 100;
266
    PID_East  = (PID_East  * (int32_t)dynamicParams.NaviGpsGain) / 100;
1612 dongfang 267
 
1775 - 268
    // GPS to nick and roll settings
269
    // A positive nick angle moves head downwards (flying forward).
270
    // A positive roll angle tilts left side downwards (flying left).
271
    // If compass heading is 0 the head of the copter is in north direction.
272
    // A positive nick angle will fly to north and a positive roll angle will fly to west.
273
    // In case of a positive north deviation/velocity the
274
    // copter should fly to south (negative nick).
275
    // In case of a positive east position deviation and a positive east velocity the
276
    // copter should fly to west (positive roll).
277
    // The influence of the GPSStickNick and GPSStickRoll variable is contrarily to the stick values
278
    // in the flight.c. Therefore a positive north deviation/velocity should result in a positive
279
    // GPSStickNick and a positive east deviation/velocity should result in a negative GPSStickRoll.
280
 
281
    coscompass = (int32_t)c_cos_8192(YawGyroHeading / GYRO_DEG_FACTOR);
282
    sincompass = (int32_t)c_sin_8192(YawGyroHeading / GYRO_DEG_FACTOR);
283
    PID_Nick =   (coscompass * PID_North + sincompass * PID_East) / 8192;
284
    PID_Roll  =  (sincompass * PID_North - coscompass * PID_East) / 8192;
285
 
286
    // limit resulting GPS control vector
287
    GPS_LimitXY(&PID_Nick, &PID_Roll, GPS_STICK_LIMIT);
288
 
289
    GPSStickNick = (int16_t)PID_Nick;
290
    GPSStickRoll = (int16_t)PID_Roll;
291
  }
1612 dongfang 292
  else // invalid GPS data or bad compass reading
293
    {
294
      GPS_Neutral(); // do nothing
295
      // reset error integral
296
      GPSPosDevIntegral_North = 0;
297
      GPSPosDevIntegral_East = 0;
298
    }
299
}
300
 
1775 - 301
void GPS_Main(void) {
1612 dongfang 302
  static uint8_t GPS_P_Delay = 0;
303
  static uint16_t beep_rythm = 0;
304
 
305
  GPS_UpdateParameter();
306
 
307
  // store home position if start of flight flag is set
1775 - 308
  if(MKFlags & MKFLAG_CALIBRATE) {
309
    if(GPS_SetCurrPosition(&HomePosition)) BeepTime = 700;
310
  }
311
 
312
  switch(GPSInfo.status) {
313
  case INVALID:  // invalid gps data
314
    GPS_Neutral();
315
    if(FlightMode != GPS_FLIGHT_MODE_FREE) {
316
      BeepTime = 100; // beep if signal is neccesary
1612 dongfang 317
    }
1775 - 318
    break;
319
  case PROCESSED: // if gps data are already processed do nothing
320
    // downcount timeout
321
    if(GPSTimeout) GPSTimeout--;
322
    // if no new data arrived within timeout set current data invalid
323
    // and therefore disable GPS
324
    else
325
      {
326
        GPS_Neutral();
1612 dongfang 327
          GPSInfo.status = INVALID;
1775 - 328
      }
329
    break;
330
  case NEWDATA: // new valid data from gps device
331
    // if the gps data quality is good
332
    beep_rythm++;
333
 
334
    if (GPS_IsSignalOK())
335
      {
336
        switch(FlightMode) // check what's to do
337
          {
338
          case GPS_FLIGHT_MODE_FREE:
339
            // update hold position to current gps position
340
            GPS_SetCurrPosition(&HoldPosition); // can get invalid if gps signal is bad
341
            // disable gps control
342
            GPS_Neutral();
343
            break;
344
 
345
          case GPS_FLIGHT_MODE_AID:
346
            if(HoldPosition.Status != INVALID)
347
              {
348
                if( GPS_IsManualControlled() ) // MK controlled by user
349
                  {
350
                    // update hold point to current gps position
351
                    GPS_SetCurrPosition(&HoldPosition);
352
                    // disable gps control
353
                    GPS_Neutral();
354
                    GPS_P_Delay = 0;
355
                  }
356
                else // GPS control active
357
                  {
358
                    if(GPS_P_Delay < 7)
359
                      { // delayed activation of P-Part for 8 cycles (8*0.25s = 2s)
360
                        GPS_P_Delay++;
361
                        GPS_SetCurrPosition(&HoldPosition); // update hold point to current gps position
362
                        GPS_PIDController(NULL); // activates only the D-Part
363
                      }
364
                    else GPS_PIDController(&HoldPosition);// activates the P&D-Part
365
                  }
366
              }
367
            else // invalid Hold Position
368
              {  // try to catch a valid hold position from gps data input
369
                GPS_SetCurrPosition(&HoldPosition);
370
                GPS_Neutral();
371
              }
372
            break;
373
 
374
          case GPS_FLIGHT_MODE_HOME:
375
            if(HomePosition.Status != INVALID)
376
              {
377
                // update hold point to current gps position
378
                // to avoid a flight back if home comming is deactivated
379
                GPS_SetCurrPosition(&HoldPosition);
380
                if( GPS_IsManualControlled() ) // MK controlled by user
381
                  {
382
                    GPS_Neutral();
383
                  }
384
                else // GPS control active
385
                  {
386
                    GPS_PIDController(&HomePosition);
387
                  }
388
              }
389
            else // bad home position
390
              {
391
                BeepTime = 50; // signal invalid home position
392
                // try to hold at least the position as a fallback option
393
 
394
                if (HoldPosition.Status != INVALID)
395
                  {
396
                    if( GPS_IsManualControlled() ) // MK controlled by user
397
                      {
398
                        GPS_Neutral();
399
                      }
400
                    else // GPS control active
401
                      {
402
                        GPS_PIDController(&HoldPosition);
403
                      }
404
                  }
405
                else
406
                  { // try to catch a valid hold position
407
                    GPS_SetCurrPosition(&HoldPosition);
408
                    GPS_Neutral();
409
                  }
410
              }
411
            break; // eof TSK_HOME
412
          default: // unhandled task
413
            GPS_Neutral();
414
            break; // eof default
415
          } // eof switch GPS_Task
416
      } // eof gps data quality is good
417
    else // gps data quality is bad
418
      { // disable gps control
419
        GPS_Neutral();
420
        if(FlightMode != GPS_FLIGHT_MODE_FREE)
421
          {
422
            // beep if signal is not sufficient
423
            if(!(GPSInfo.flags & FLAG_GPSFIXOK) && !(beep_rythm % 5)) BeepTime = 100;
424
            else if (GPSInfo.satnum < staticParams.NaviGpsMinSat && !(beep_rythm % 5)) BeepTime = 10;
425
          }
426
      }
1612 dongfang 427
      // set current data as processed to avoid further calculations on the same gps data
1775 - 428
    GPSInfo.status = PROCESSED;
429
    break;
430
  } // eof GPSInfo.status
1612 dongfang 431
}
432