Subversion Repositories FlightCtrl

Rev

Go to most recent revision | Details | 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>
53
#include "ubx.h"
54
#include "mymath.h"
55
#include "timer0.h"
56
#include "uart0.h"
57
#include "rc.h"
58
#include "eeprom.h"
59
 
60
typedef enum
61
  {
62
    GPS_FLIGHT_MODE_UNDEF,
63
    GPS_FLIGHT_MODE_FREE,
64
    GPS_FLIGHT_MODE_AID,
65
    GPS_FLIGHT_MODE_HOME,
66
  } FlightMode_t;
67
 
68
#define GPS_POSINTEGRAL_LIMIT 32000
69
#define GPS_STICK_LIMIT         45              // limit of gps stick control to avoid critical flight attitudes
70
#define GPS_P_LIMIT                     25
71
 
72
 
73
typedef struct
74
{
75
  int32_t Longitude;
76
  int32_t Latitude;
77
  int32_t Altitude;
78
  Status_t Status;
79
} GPS_Pos_t;
80
 
81
// GPS coordinates for hold position
82
GPS_Pos_t HoldPosition  = {0,0,0,INVALID};
83
// GPS coordinates for home position
84
GPS_Pos_t HomePosition  = {0,0,0,INVALID};
85
// the current flight mode
86
FlightMode_t FlightMode = GPS_FLIGHT_MODE_UNDEF;
87
 
88
 
89
// ---------------------------------------------------------------------------------
90
void GPS_UpdateParameter(void)
91
{
92
  static FlightMode_t FlightModeOld = GPS_FLIGHT_MODE_UNDEF;
93
 
94
  if((RC_Quality < 100) || (MKFlags & MKFLAG_EMERGENCY_LANDING))
95
    {
96
      FlightMode = GPS_FLIGHT_MODE_FREE;
97
    }
98
  else
99
    {
100
      if     (dynamicParams.NaviGpsModeControl <  50) FlightMode = GPS_FLIGHT_MODE_AID;
101
      else if(dynamicParams.NaviGpsModeControl < 180) FlightMode = GPS_FLIGHT_MODE_FREE;
102
      else                                                FlightMode = GPS_FLIGHT_MODE_HOME;
103
    }
104
  if (FlightMode != FlightModeOld)
105
    {
106
      BeepTime = 100;
107
    }
108
  FlightModeOld = FlightMode;
109
}
110
 
111
 
112
 
113
// ---------------------------------------------------------------------------------
114
// This function defines a good GPS signal condition
115
uint8_t GPS_IsSignalOK(void)
116
{
117
  static uint8_t GPSFix = 0;
118
  if( (GPSInfo.status != INVALID)  && (GPSInfo.satfix == SATFIX_3D) && (GPSInfo.flags & FLAG_GPSFIXOK) && ((GPSInfo.satnum >= staticParams.NaviGpsMinSat) || GPSFix))
119
    {
120
      GPSFix = 1;
121
      return(1);
122
 
123
    }
124
  else return (0);
125
 
126
}
127
// ---------------------------------------------------------------------------------
128
// rescale xy-vector length to  limit
129
uint8_t GPS_LimitXY(int32_t *x, int32_t *y, int32_t limit)
130
{
131
  uint8_t retval = 0;
132
  int32_t len;
133
  len = (int32_t)c_sqrt(*x * *x + *y * *y);
134
  if (len > limit)
135
    {
136
      // normalize control vector components to the limit
137
      *x  = (*x  * limit) / len;
138
      *y  = (*y  * limit) / len;
139
      retval = 1;
140
    }
141
  return(retval);
142
}
143
 
144
// checks nick and roll sticks for manual control
145
uint8_t GPS_IsManualControlled(void)
146
{
147
  if ( (abs(PPM_in[staticParams.ChannelAssignment[CH_NICK]]) < staticParams.NaviStickThreshold) && (abs(PPM_in[staticParams.ChannelAssignment[CH_ROLL]]) < staticParams.NaviStickThreshold)) return 0;
148
  else return 1;
149
}
150
 
151
// set given position to current gps position
152
uint8_t GPS_SetCurrPosition(GPS_Pos_t * pGPSPos)
153
{
154
  uint8_t retval = 0;
155
  if(pGPSPos == NULL) return(retval);   // bad pointer
156
 
157
  if(GPS_IsSignalOK())
158
    {   // is GPS signal condition is fine
159
      pGPSPos->Longitude        = GPSInfo.longitude;
160
      pGPSPos->Latitude = GPSInfo.latitude;
161
      pGPSPos->Altitude = GPSInfo.altitude;
162
      pGPSPos->Status   = NEWDATA;
163
      retval = 1;
164
    }
165
  else
166
    {   // bad GPS signal condition
167
      pGPSPos->Status = INVALID;
168
      retval = 0;
169
    }
170
  return(retval);
171
}
172
 
173
// clear position
174
uint8_t GPS_ClearPosition(GPS_Pos_t * pGPSPos)
175
{
176
  uint8_t retval = 0;
177
  if(pGPSPos == NULL) return(retval);   // bad pointer
178
  else
179
    {
180
      pGPSPos->Longitude        = 0;
181
      pGPSPos->Latitude = 0;
182
      pGPSPos->Altitude = 0;
183
      pGPSPos->Status   = INVALID;
184
      retval = 1;
185
    }
186
  return (retval);
187
}
188
 
189
// disable GPS control sticks
190
void GPS_Neutral(void)
191
{
192
  GPSStickNick = 0;
193
  GPSStickRoll = 0;
194
}
195
 
196
// calculates the GPS control stick values from the deviation to target position
197
// if the pointer to the target positin is NULL or is the target position invalid
198
// then the P part of the controller is deactivated.
199
void GPS_PIDController(GPS_Pos_t *pTargetPos)
200
{
201
  static int32_t PID_Nick, PID_Roll;
202
  int32_t coscompass, sincompass;
203
  int32_t GPSPosDev_North, GPSPosDev_East; // Position deviation in cm
204
  int32_t P_North = 0, D_North = 0, P_East = 0, D_East = 0, I_North = 0, I_East = 0;
205
  int32_t PID_North = 0, PID_East = 0;
206
  static int32_t cos_target_latitude = 1;
207
  static int32_t GPSPosDevIntegral_North = 0, GPSPosDevIntegral_East = 0;
208
  static GPS_Pos_t *pLastTargetPos = 0;
209
 
210
  // if GPS data and Compass are ok
211
  if( GPS_IsSignalOK() && (CompassHeading >= 0) )
212
    {
213
 
214
      if(pTargetPos != NULL) // if there is a target position
215
        {
216
          if(pTargetPos->Status != INVALID) // and the position data are valid
217
            {
218
              // if the target data are updated or the target pointer has changed
219
              if ((pTargetPos->Status != PROCESSED) || (pTargetPos != pLastTargetPos) )
220
                {
221
                  // reset error integral
222
                  GPSPosDevIntegral_North = 0;
223
                  GPSPosDevIntegral_East = 0;
224
                  // recalculate latitude projection
225
                  cos_target_latitude = (int32_t)c_cos_8192((int16_t)(pTargetPos->Latitude/10000000L));
226
                  // remember last target pointer
227
                  pLastTargetPos = pTargetPos;
228
                  // mark data as processed
229
                  pTargetPos->Status = PROCESSED;
230
                }
231
              // calculate position deviation from latitude and longitude differences
232
              GPSPosDev_North = (GPSInfo.latitude - pTargetPos->Latitude); // to calculate real cm we would need *111/100 additionally
233
              GPSPosDev_East  = (GPSInfo.longitude - pTargetPos->Longitude); // to calculate real cm we would need *111/100 additionally
234
              // calculate latitude projection
235
              GPSPosDev_East  *= cos_target_latitude;
236
              GPSPosDev_East /= 8192;
237
            }
238
          else // no valid target position available
239
            {
240
              // reset error
241
              GPSPosDev_North = 0;
242
              GPSPosDev_East = 0;
243
              // reset error integral
244
              GPSPosDevIntegral_North = 0;
245
              GPSPosDevIntegral_East = 0;
246
            }
247
        }
248
      else // no target position available
249
        {
250
          // reset error
251
          GPSPosDev_North = 0;
252
          GPSPosDev_East = 0;
253
          // reset error integral
254
          GPSPosDevIntegral_North = 0;
255
          GPSPosDevIntegral_East = 0;
256
        }
257
 
258
      //Calculate PID-components of the controller
259
 
260
      // D-Part
261
      D_North = ((int32_t)dynamicParams.NaviGpsD * GPSInfo.velnorth)/512;
262
      D_East =  ((int32_t)dynamicParams.NaviGpsD * GPSInfo.veleast)/512;
263
 
264
      // P-Part
265
      P_North = ((int32_t)dynamicParams.NaviGpsP * GPSPosDev_North)/2048;
266
      P_East =  ((int32_t)dynamicParams.NaviGpsP * GPSPosDev_East)/2048;
267
 
268
      // I-Part
269
      I_North = ((int32_t)dynamicParams.NaviGpsI * GPSPosDevIntegral_North)/8192;
270
      I_East =  ((int32_t)dynamicParams.NaviGpsI * GPSPosDevIntegral_East)/8192;
271
 
272
 
273
      // combine P & I
274
      PID_North = P_North + I_North;
275
      PID_East  = P_East  + I_East;
276
      if(!GPS_LimitXY(&PID_North, &PID_East, GPS_P_LIMIT))
277
        {
278
          GPSPosDevIntegral_North += GPSPosDev_North/16;
279
          GPSPosDevIntegral_East  += GPSPosDev_East/16;
280
          GPS_LimitXY(&GPSPosDevIntegral_North, &GPSPosDevIntegral_East, GPS_POSINTEGRAL_LIMIT);
281
        }
282
 
283
      // combine PI- and D-Part
284
      PID_North += D_North;
285
      PID_East  += D_East;
286
 
287
 
288
      // scale combination with gain.
289
      PID_North = (PID_North * (int32_t)dynamicParams.NaviGpsGain) / 100;
290
      PID_East  = (PID_East  * (int32_t)dynamicParams.NaviGpsGain) / 100;
291
 
292
      // GPS to nick and roll settings
293
 
294
      // A positive nick angle moves head downwards (flying forward).
295
      // A positive roll angle tilts left side downwards (flying left).
296
      // If compass heading is 0 the head of the copter is in north direction.
297
      // A positive nick angle will fly to north and a positive roll angle will fly to west.
298
      // In case of a positive north deviation/velocity the
299
      // copter should fly to south (negative nick).
300
      // In case of a positive east position deviation and a positive east velocity the
301
      // copter should fly to west (positive roll).
302
      // The influence of the GPSStickNick and GPSStickRoll variable is contrarily to the stick values
303
      // in the flight.c. Therefore a positive north deviation/velocity should result in a positive
304
      // GPSStickNick and a positive east deviation/velocity should result in a negative GPSStickRoll.
305
 
306
      coscompass = (int32_t)c_cos_8192(YawGyroHeading / GYRO_DEG_FACTOR);
307
      sincompass = (int32_t)c_sin_8192(YawGyroHeading / GYRO_DEG_FACTOR);
308
      PID_Nick =   (coscompass * PID_North + sincompass * PID_East) / 8192;
309
      PID_Roll  =  (sincompass * PID_North - coscompass * PID_East) / 8192;
310
 
311
 
312
      // limit resulting GPS control vector
313
      GPS_LimitXY(&PID_Nick, &PID_Roll, GPS_STICK_LIMIT);
314
 
315
      GPSStickNick = (int16_t)PID_Nick;
316
      GPSStickRoll = (int16_t)PID_Roll;
317
    }
318
  else // invalid GPS data or bad compass reading
319
    {
320
      GPS_Neutral(); // do nothing
321
      // reset error integral
322
      GPSPosDevIntegral_North = 0;
323
      GPSPosDevIntegral_East = 0;
324
    }
325
}
326
 
327
 
328
 
329
 
330
void GPS_Main(void)
331
{
332
  static uint8_t GPS_P_Delay = 0;
333
  static uint16_t beep_rythm = 0;
334
 
335
  GPS_UpdateParameter();
336
 
337
  // store home position if start of flight flag is set
338
  if(MKFlags & MKFLAG_CALIBRATE)
339
    {
340
      if(GPS_SetCurrPosition(&HomePosition)) BeepTime = 700;
341
    }
342
 
343
  switch(GPSInfo.status)
344
    {
345
    case INVALID:  // invalid gps data
346
      GPS_Neutral();
347
      if(FlightMode != GPS_FLIGHT_MODE_FREE)
348
        {
349
          BeepTime = 100; // beep if signal is neccesary
350
        }
351
      break;
352
    case PROCESSED: // if gps data are already processed do nothing
353
      // downcount timeout
354
      if(GPSTimeout) GPSTimeout--;
355
      // if no new data arrived within timeout set current data invalid
356
      // and therefore disable GPS
357
      else
358
        {
359
          GPS_Neutral();
360
          GPSInfo.status = INVALID;
361
        }
362
      break;
363
    case NEWDATA: // new valid data from gps device
364
      // if the gps data quality is good
365
      beep_rythm++;
366
 
367
      if (GPS_IsSignalOK())
368
        {
369
          switch(FlightMode) // check what's to do
370
            {
371
            case GPS_FLIGHT_MODE_FREE:
372
              // update hold position to current gps position
373
              GPS_SetCurrPosition(&HoldPosition); // can get invalid if gps signal is bad
374
              // disable gps control
375
              GPS_Neutral();
376
              break;
377
 
378
            case GPS_FLIGHT_MODE_AID:
379
              if(HoldPosition.Status != INVALID)
380
                {
381
                  if( GPS_IsManualControlled() ) // MK controlled by user
382
                    {
383
                      // update hold point to current gps position
384
                      GPS_SetCurrPosition(&HoldPosition);
385
                      // disable gps control
386
                      GPS_Neutral();
387
                      GPS_P_Delay = 0;
388
                    }
389
                  else // GPS control active
390
                    {
391
                      if(GPS_P_Delay < 7)
392
                        { // delayed activation of P-Part for 8 cycles (8*0.25s = 2s)
393
                          GPS_P_Delay++;
394
                          GPS_SetCurrPosition(&HoldPosition); // update hold point to current gps position
395
                          GPS_PIDController(NULL); // activates only the D-Part
396
                        }
397
                      else GPS_PIDController(&HoldPosition);// activates the P&D-Part
398
                    }
399
                }
400
              else // invalid Hold Position
401
                {  // try to catch a valid hold position from gps data input
402
                  GPS_SetCurrPosition(&HoldPosition);
403
                  GPS_Neutral();
404
                }
405
              break;
406
 
407
            case GPS_FLIGHT_MODE_HOME:
408
              if(HomePosition.Status != INVALID)
409
                {
410
                  // update hold point to current gps position
411
                  // to avoid a flight back if home comming is deactivated
412
                  GPS_SetCurrPosition(&HoldPosition);
413
                  if( GPS_IsManualControlled() ) // MK controlled by user
414
                    {
415
                      GPS_Neutral();
416
                    }
417
                  else // GPS control active
418
                    {
419
                      GPS_PIDController(&HomePosition);
420
                    }
421
                }
422
              else // bad home position
423
                {
424
                  BeepTime = 50; // signal invalid home position
425
                  // try to hold at least the position as a fallback option
426
 
427
                  if (HoldPosition.Status != INVALID)
428
                    {
429
                      if( GPS_IsManualControlled() ) // MK controlled by user
430
                        {
431
                          GPS_Neutral();
432
                        }
433
                      else // GPS control active
434
                        {
435
                          GPS_PIDController(&HoldPosition);
436
                        }
437
                    }
438
                  else
439
                    { // try to catch a valid hold position
440
                      GPS_SetCurrPosition(&HoldPosition);
441
                      GPS_Neutral();
442
                    }
443
                }
444
              break; // eof TSK_HOME
445
            default: // unhandled task
446
              GPS_Neutral();
447
              break; // eof default
448
            } // eof switch GPS_Task
449
        } // eof gps data quality is good
450
      else // gps data quality is bad
451
        {       // disable gps control
452
          GPS_Neutral();
453
          if(FlightMode != GPS_FLIGHT_MODE_FREE)
454
            {
455
              // beep if signal is not sufficient
456
              if(!(GPSInfo.flags & FLAG_GPSFIXOK) && !(beep_rythm % 5)) BeepTime = 100;
457
              else if (GPSInfo.satnum < staticParams.NaviGpsMinSat && !(beep_rythm % 5)) BeepTime = 10;
458
            }
459
        }
460
      // set current data as processed to avoid further calculations on the same gps data
461
      GPSInfo.status = PROCESSED;
462
      break;
463
    } // eof GPSInfo.status
464
}
465