Subversion Repositories FlightCtrl

Rev

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