Subversion Repositories FlightCtrl

Rev

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

Rev Author Line No. Line
2039 - 1
// Navigation with a GPS directly attached to the FC's UART1.
2
 
3
#include <inttypes.h>
4
#include <stdlib.h>
5
#include <stddef.h>
6
//#include "mymath.h"
7
//#include "timer0.h"
8
//#include "uart1.h"
9
//#include "rc.h"
10
//#include "eeprom.h"
11
#include "ubx.h"
12
#include "configuration.h"
13
#include "controlMixer.h"
14
#include "output.h"
15
#include "isqrt.h"
16
#include "attitude.h"
17
#include "dongfangMath.h"
18
 
19
typedef enum {
20
  GPS_FLIGHT_MODE_UNDEF,
21
  GPS_FLIGHT_MODE_FREE,
22
  GPS_FLIGHT_MODE_AID,
23
  GPS_FLIGHT_MODE_HOME,
24
} FlightMode_t;
25
 
26
#define GPS_POSINTEGRAL_LIMIT 32000
27
#define GPS_STICK_LIMIT         45              // limit of gps stick control to avoid critical flight attitudes
28
#define GPS_P_LIMIT                     25
29
 
30
typedef struct {
31
  int32_t longitude;
32
  int32_t latitude;
33
  int32_t altitude;
34
  Status_t status;
35
} GPS_Pos_t;
36
 
37
// GPS coordinates for hold position
38
GPS_Pos_t holdPosition = { 0, 0, 0, INVALID };
39
// GPS coordinates for home position
40
GPS_Pos_t homePosition = { 0, 0, 0, INVALID };
41
// the current flight mode
42
FlightMode_t flightMode = GPS_FLIGHT_MODE_UNDEF;
43
 
44
// ---------------------------------------------------------------------------------
45
void GPS_updateFlightMode(void) {
46
  static FlightMode_t flightModeOld = GPS_FLIGHT_MODE_UNDEF;
47
 
48
  if (controlMixer_getSignalQuality() <= SIGNAL_BAD
49
      || MKFlags & MKFLAG_EMERGENCY_FLIGHT) {
2045 - 50
    flightMode = GPS_FLIGHT_MODE_HOME;
2039 - 51
  } else {
2045 - 52
    if (dynamicParams.naviMode < 50)
53
      flightMode = GPS_FLIGHT_MODE_FREE;
54
    else if (dynamicParams.naviMode < 180)
2039 - 55
      flightMode = GPS_FLIGHT_MODE_AID;
56
    else
57
      flightMode = GPS_FLIGHT_MODE_HOME;
58
  }
59
 
60
  if (flightMode != flightModeOld) {
61
    beep(100);
62
    flightModeOld = flightMode;
63
  }
2045 - 64
 
65
  debugOut.analog[31] = flightMode;
2039 - 66
}
67
 
68
// ---------------------------------------------------------------------------------
69
// This function defines a good GPS signal condition
70
uint8_t GPS_isSignalOK(void) {
71
  static uint8_t GPSFix = 0;
72
  if ((GPSInfo.status != INVALID) && (GPSInfo.satfix == SATFIX_3D)
73
      && (GPSInfo.flags & FLAG_GPSFIXOK)
74
      && ((GPSInfo.satnum >= staticParams.GPSMininumSatellites) || GPSFix)) {
75
    GPSFix = 1;
76
    return 1;
77
  } else
78
    return (0);
79
}
80
 
81
// ---------------------------------------------------------------------------------
82
// rescale xy-vector length to  limit
83
uint8_t GPS_limitXY(int32_t *x, int32_t *y, int32_t limit) {
84
  int32_t len;
85
  len = isqrt32(*x * *x + *y * *y);
86
  if (len > limit) {
87
    // normalize control vector components to the limit
88
    *x = (*x * limit) / len;
89
    *y = (*y * limit) / len;
90
    return 1;
91
  }
92
  return 0;
93
}
94
 
95
// checks nick and roll sticks for manual control
2044 - 96
uint8_t GPS_isManuallyControlled(int16_t* sticks) {
97
  if (sticks[CONTROL_PITCH] < staticParams.naviStickThreshold
98
      && sticks[CONTROL_ROLL] < staticParams.naviStickThreshold)
2039 - 99
    return 0;
100
  else
101
    return 1;
102
}
103
 
104
// set given position to current gps position
2045 - 105
uint8_t GPS_writeCurrPositionTo(GPS_Pos_t * pGPSPos) {
2039 - 106
  if (pGPSPos == NULL)
2044 - 107
    return 0; // bad pointer
2039 - 108
 
109
  if (GPS_isSignalOK()) { // is GPS signal condition is fine
110
    pGPSPos->longitude = GPSInfo.longitude;
111
    pGPSPos->latitude = GPSInfo.latitude;
112
    pGPSPos->altitude = GPSInfo.altitude;
113
    pGPSPos->status = NEWDATA;
2044 - 114
    return 1;
2039 - 115
  } else { // bad GPS signal condition
116
    pGPSPos->status = INVALID;
2044 - 117
    return 0;
2039 - 118
  }
119
}
120
 
121
// clear position
122
uint8_t GPS_clearPosition(GPS_Pos_t * pGPSPos) {
123
  if (pGPSPos == NULL)
2044 - 124
    return 0; // bad pointer
2039 - 125
  else {
126
    pGPSPos->longitude = 0;
127
    pGPSPos->latitude = 0;
128
    pGPSPos->altitude = 0;
129
    pGPSPos->status = INVALID;
130
  }
2044 - 131
  return 1;
2039 - 132
}
133
 
134
// calculates the GPS control stick values from the deviation to target position
135
// if the pointer to the target positin is NULL or is the target position invalid
136
// then the P part of the controller is deactivated.
137
void GPS_PIDController(GPS_Pos_t *pTargetPos, int16_t* sticks) {
138
  static int32_t PID_Nick, PID_Roll;
139
  int32_t coscompass, sincompass;
140
  int32_t GPSPosDev_North, GPSPosDev_East; // Position deviation in cm
2044 - 141
  int32_t P_North = 0, D_North = 0, P_East = 0, D_East = 0, I_North = 0, I_East = 0;
2039 - 142
  int32_t PID_North = 0, PID_East = 0;
143
  static int32_t cos_target_latitude = 1;
144
  static int32_t GPSPosDevIntegral_North = 0, GPSPosDevIntegral_East = 0;
145
  static GPS_Pos_t *pLastTargetPos = 0;
146
 
147
  // if GPS data and Compass are ok
2042 - 148
  if (GPS_isSignalOK() && (magneticHeading >= 0)) {
2044 - 149
    if (pTargetPos != NULL) { // if there is a target position
150
      if (pTargetPos->status != INVALID) { // and the position data are valid
2039 - 151
        // if the target data are updated or the target pointer has changed
152
        if ((pTargetPos->status != PROCESSED)
153
            || (pTargetPos != pLastTargetPos)) {
154
          // reset error integral
155
          GPSPosDevIntegral_North = 0;
156
          GPSPosDevIntegral_East = 0;
157
          // recalculate latitude projection
2045 - 158
          cos_target_latitude = cos_360(pTargetPos->latitude / 10000000L);
2039 - 159
          // remember last target pointer
160
          pLastTargetPos = pTargetPos;
161
          // mark data as processed
162
          pTargetPos->status = PROCESSED;
163
        }
164
        // calculate position deviation from latitude and longitude differences
165
        GPSPosDev_North = (GPSInfo.latitude - pTargetPos->latitude); // to calculate real cm we would need *111/100 additionally
166
        GPSPosDev_East = (GPSInfo.longitude - pTargetPos->longitude); // to calculate real cm we would need *111/100 additionally
167
        // calculate latitude projection
168
        GPSPosDev_East *= cos_target_latitude;
169
        GPSPosDev_East >>= MATH_UNIT_FACTOR_LOG;
170
      } else { // no valid target position available
171
        // reset error
172
        GPSPosDev_North = 0;
173
        GPSPosDev_East = 0;
174
        // reset error integral
175
        GPSPosDevIntegral_North = 0;
176
        GPSPosDevIntegral_East = 0;
177
      }
178
    } else { // no target position available
179
      // reset error
180
      GPSPosDev_North = 0;
181
      GPSPosDev_East = 0;
182
      // reset error integral
183
      GPSPosDevIntegral_North = 0;
184
      GPSPosDevIntegral_East = 0;
185
    }
186
 
187
    //Calculate PID-components of the controller
188
 
189
    // D-Part
190
    D_North = ((int32_t) staticParams.naviD * GPSInfo.velnorth) / 512;
191
    D_East = ((int32_t) staticParams.naviD * GPSInfo.veleast) / 512;
192
 
193
    // P-Part
194
    P_North = ((int32_t) staticParams.naviP * GPSPosDev_North) / 2048;
195
    P_East = ((int32_t) staticParams.naviP * GPSPosDev_East) / 2048;
196
 
197
    // I-Part
198
    I_North = ((int32_t) staticParams.naviI * GPSPosDevIntegral_North)
199
        / 8192;
200
    I_East = ((int32_t) staticParams.naviI * GPSPosDevIntegral_East) / 8192;
201
 
202
    // combine P & I
203
    PID_North = P_North + I_North;
204
    PID_East = P_East + I_East;
205
    if (!GPS_limitXY(&PID_North, &PID_East, GPS_P_LIMIT)) {
206
      GPSPosDevIntegral_North += GPSPosDev_North / 16;
207
      GPSPosDevIntegral_East += GPSPosDev_East / 16;
208
      GPS_limitXY(&GPSPosDevIntegral_North, &GPSPosDevIntegral_East,
209
          GPS_POSINTEGRAL_LIMIT);
210
    }
211
 
212
    // combine PI- and D-Part
213
    PID_North += D_North;
214
    PID_East += D_East;
215
 
216
    // scale combination with gain.
217
    // dongfang: Lets not do that. P I and D can be scaled instead.
218
    // PID_North = (PID_North * (int32_t) staticParams.NaviGpsGain) / 100;
219
    // PID_East = (PID_East * (int32_t) staticParams.NaviGpsGain) / 100;
220
 
221
    // GPS to nick and roll settings
222
    // A positive nick angle moves head downwards (flying forward).
223
    // A positive roll angle tilts left side downwards (flying left).
224
    // If compass heading is 0 the head of the copter is in north direction.
225
    // A positive nick angle will fly to north and a positive roll angle will fly to west.
226
    // In case of a positive north deviation/velocity the
227
    // copter should fly to south (negative nick).
228
    // In case of a positive east position deviation and a positive east velocity the
229
    // copter should fly to west (positive roll).
230
    // The influence of the GPSStickNick and GPSStickRoll variable is contrarily to the stick values
231
    // in the flight.c. Therefore a positive north deviation/velocity should result in a positive
232
    // GPSStickNick and a positive east deviation/velocity should result in a negative GPSStickRoll.
233
 
2044 - 234
    coscompass = cos_360(yawGyroHeading / GYRO_DEG_FACTOR_YAW);
235
    sincompass = sin_360(yawGyroHeading / GYRO_DEG_FACTOR_YAW);
236
 
2039 - 237
    PID_Nick = (coscompass * PID_North + sincompass * PID_East) >> MATH_UNIT_FACTOR_LOG;
238
    PID_Roll = (sincompass * PID_North - coscompass * PID_East) >> MATH_UNIT_FACTOR_LOG;
239
 
240
    // limit resulting GPS control vector
241
    GPS_limitXY(&PID_Nick, &PID_Roll, GPS_STICK_LIMIT);
242
 
2045 - 243
    debugOut.analog[27] = PID_Nick;
244
    debugOut.analog[28] = PID_Roll;
245
 
246
    sticks[CONTROL_PITCH] += PID_Nick;
247
    sticks[CONTROL_ROLL]  += PID_Roll;
248
 
2039 - 249
  } else { // invalid GPS data or bad compass reading
250
    // reset error integral
251
    GPSPosDevIntegral_North = 0;
252
    GPSPosDevIntegral_East = 0;
253
  }
254
}
255
 
256
void navigation_periodicTask(int16_t* sticks) {
257
  static uint8_t GPS_P_Delay = 0;
258
  static uint16_t beep_rythm = 0;
259
 
260
  GPS_updateFlightMode();
261
 
262
  // store home position if start of flight flag is set
263
  if (MKFlags & MKFLAG_CALIBRATE) {
2044 - 264
    MKFlags &= ~(MKFLAG_CALIBRATE);
2045 - 265
    if (GPS_writeCurrPositionTo(&homePosition)) {
266
        homePosition.latitude += 9000L;
267
        beep(500);
268
      }
269
    }
2039 - 270
 
271
  switch (GPSInfo.status) {
272
  case INVALID: // invalid gps data
273
    if (flightMode != GPS_FLIGHT_MODE_FREE) {
274
      beep(100); // beep if signal is neccesary
275
    }
276
    break;
277
  case PROCESSED: // if gps data are already processed do nothing
278
    // downcount timeout
279
    if (GPSTimeout)
280
      GPSTimeout--;
281
    // if no new data arrived within timeout set current data invalid
282
    // and therefore disable GPS
283
    else {
284
      GPSInfo.status = INVALID;
285
    }
286
    break;
287
  case NEWDATA: // new valid data from gps device
288
    // if the gps data quality is good
289
    beep_rythm++;
290
    if (GPS_isSignalOK()) {
291
      switch (flightMode) { // check what's to do
292
      case GPS_FLIGHT_MODE_FREE:
293
        // update hold position to current gps position
2045 - 294
        GPS_writeCurrPositionTo(&holdPosition); // can get invalid if gps signal is bad
2039 - 295
        // disable gps control
296
        break;
297
 
298
      case GPS_FLIGHT_MODE_AID:
299
        if (holdPosition.status != INVALID) {
300
          if (GPS_isManuallyControlled(sticks)) { // MK controlled by user
301
            // update hold point to current gps position
2045 - 302
            GPS_writeCurrPositionTo(&holdPosition);
2039 - 303
            // disable gps control
304
            GPS_P_Delay = 0;
305
          } else { // GPS control active
306
            if (GPS_P_Delay < 7) {
307
              // delayed activation of P-Part for 8 cycles (8*0.25s = 2s)
308
              GPS_P_Delay++;
2045 - 309
              GPS_writeCurrPositionTo(&holdPosition); // update hold point to current gps position
2039 - 310
              GPS_PIDController(NULL, sticks); // activates only the D-Part
311
            } else
312
              GPS_PIDController(&holdPosition, sticks); // activates the P&D-Part
313
          }
314
        } else // invalid Hold Position
315
        { // try to catch a valid hold position from gps data input
2045 - 316
          GPS_writeCurrPositionTo(&holdPosition);
2039 - 317
        }
318
        break;
319
 
320
      case GPS_FLIGHT_MODE_HOME:
321
        if (homePosition.status != INVALID) {
322
          // update hold point to current gps position
323
          // to avoid a flight back if home comming is deactivated
2045 - 324
          GPS_writeCurrPositionTo(&holdPosition);
2039 - 325
          if (GPS_isManuallyControlled(sticks)) // MK controlled by user
326
          {
327
          } else {// GPS control active
328
            GPS_PIDController(&homePosition, sticks);
329
          }
330
        } else {
331
          // bad home position
332
          beep(50); // signal invalid home position
333
          // try to hold at least the position as a fallback option
334
 
335
          if (holdPosition.status != INVALID) {
336
            if (GPS_isManuallyControlled(sticks)) {
337
              // MK controlled by user
338
            } else {
339
              // GPS control active
340
              GPS_PIDController(&holdPosition, sticks);
341
            }
342
          } else { // try to catch a valid hold position
2045 - 343
            GPS_writeCurrPositionTo(&holdPosition);
2039 - 344
          }
345
        }
346
        break; // eof TSK_HOME
347
      default: // unhandled task
348
        break; // eof default
349
      } // eof switch GPS_Task
350
    } // eof gps data quality is good
351
    else // gps data quality is bad
352
    { // disable gps control
353
      if (flightMode != GPS_FLIGHT_MODE_FREE) {
354
        // beep if signal is not sufficient
355
        if (!(GPSInfo.flags & FLAG_GPSFIXOK) && !(beep_rythm % 5))
356
          beep(100);
357
        else if (GPSInfo.satnum < staticParams.GPSMininumSatellites
358
            && !(beep_rythm % 5))
359
          beep(10);
360
      }
361
    }
362
    // set current data as processed to avoid further calculations on the same gps data
363
    GPSInfo.status = PROCESSED;
364
    break;
365
  } // eof GPSInfo.status
2044 - 366
 
367
  debugOut.analog[11] = GPSInfo.satnum;
2039 - 368
}
369
 
2044 - 370