forked from mahowik/mahowii
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GPS.cpp
1980 lines (1711 loc) · 76.5 KB
/
GPS.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "Arduino.h"
#include "config.h"
#include "def.h"
#include "types.h"
#include "GPS.h"
#include "Serial.h"
#include "Sensors.h"
#include "MahoWii.h"
#include "EEPROM.h"
#include "AltHold.h"
#include "Math.h"
#include <math.h>
#if GPS
//Function prototypes for other GPS functions
//These perhaps could go to the gps.h file, however these are local to the gps.cpp
static void GPS_bearing(int32_t* lat1, int32_t* lon1, int32_t* lat2, int32_t* lon2, int32_t* bearing);
static void GPS_distance_cm(int32_t* lat1, int32_t* lon1, int32_t* lat2, int32_t* lon2, uint32_t* dist);
static void calculateDistanceToHome(uint32_t* dist);
static void GPS_calc_velocity(void);
#ifndef INS_PH_NAV_ON
static void GPS_calc_location_error(int32_t* target_lat, int32_t* target_lng, int32_t* gps_lat, int32_t* gps_lng);
#endif
static uint16_t GPS_calc_desired_speed(uint16_t max_speed, bool _slow);
static void GPS_calc_nav_rate(uint16_t max_speed);
int32_t wrap_18000(int32_t ang);
static bool check_missed_wp(void);
void GPS_calc_longitude_scaling(int32_t lat);
static void GPS_update_crosstrack(void);
int32_t wrap_36000(int32_t ang);
typedef struct PID_PARAM_ {
float kP;
float kI;
float kD;
float Imax;
} PID_PARAM;
PID_PARAM posholdPID_PARAM;
PID_PARAM poshold_ratePID_PARAM;
PID_PARAM navPID_PARAM;
typedef struct PID_ {
float integrator; // integrator value
int32_t last_input; // last input for derivative
float lastderivative; // last derivative for low-pass filter
//float output;
float derivative;
} PID;
PID posholdPID[2];
PID poshold_ratePID[2];
PID navPID[2];
int32_t get_P(int32_t error, struct PID_PARAM_* pid) {
return (float) error * pid->kP;
}
int32_t get_I(int32_t error, float* dt, struct PID_* pid, struct PID_PARAM_* pid_param) {
pid->integrator += ((float) error * pid_param->kI) * *dt;
pid->integrator = constrain(pid->integrator, -pid_param->Imax, pid_param->Imax);
return pid->integrator;
}
int32_t get_D(int32_t input, float* dt, struct PID_* pid, struct PID_PARAM_* pid_param) { // dt in milliseconds
pid->derivative = (input - pid->last_input) / *dt;
/// Low pass filter cut frequency for derivative calculation.
float filter = 7.9577e-3; // Set to "1 / ( 2 * PI * f_cut )";
// Examples for _filter:
// f_cut = 10 Hz -> _filter = 15.9155e-3
// f_cut = 15 Hz -> _filter = 10.6103e-3
// f_cut = 20 Hz -> _filter = 7.9577e-3
// f_cut = 25 Hz -> _filter = 6.3662e-3
// f_cut = 30 Hz -> _filter = 5.3052e-3
// discrete low pass filter, cuts out the
// high frequency noise that can drive the controller crazy
pid->derivative = pid->lastderivative + (*dt / (filter + *dt)) * (pid->derivative - pid->lastderivative);
// update state
pid->last_input = input;
pid->lastderivative = pid->derivative;
// add in derivative component
return pid_param->kD * pid->derivative;
}
void reset_PID(struct PID_* pid) {
pid->integrator = 0;
pid->last_input = 0;
pid->lastderivative = 0;
}
#define _X 1
#define _Y 0
//#define RADX100 0.000174532925
uint8_t GPS_Frame; // a valid GPS_Frame was detected, and data is ready for nav computation
static float dTnav; // Delta Time in milliseconds for navigation computations, updated with every good GPS read
int16_t gpsActualSpeed[2] = { 0, 0 };
static float GPS_scaleLonDown; // this is used to offset the shrinking longitude as we go towards the poles
// The difference between the desired rate of travel and the actual rate of travel
// updated after GPS read - 5-10hz
static int16_t rate_error[2];
int32_t gpsDistanceToHome[2];
#ifdef INS_PH_NAV_ON
int32_t positionToHold[2];
#else
int32_t gpsPositionError[2];
#endif
static int32_t GPS_WP[2]; //Currently used WP
static int32_t GPS_FROM[2]; //the pervious waypoint for precise track following
int32_t target_bearing; // This is the angle from the copter to the "next_WP" location in degrees * 100
static int32_t original_target_bearing; // deg * 100, The original angle to the next_WP when the next_WP was set, Also used to check when we pass a WP
static int16_t crosstrack_error; // The amount of angle correction applied to target_bearing to bring the copter back on its optimum path
uint32_t wp_distance; // distance between plane and next_WP in cm
static uint16_t waypoint_speed_gov; // used for slow speed wind up when start navigation;
////////////////////////////////////////////////////////////////////////////////////
// moving average filter variables
////////////////////////////////////////////////////////////////////////////////////
#if defined(GPS_FILTERING) && (!defined(INS_PH_NAV_ON))
#define GPS_FILTER_VECTOR_LENGTH 5
static uint8_t GPS_filter_index = 0;
static int32_t GPS_filter[2][GPS_FILTER_VECTOR_LENGTH];
static int32_t GPS_filter_sum[2];
static int32_t GPS_read[2];
static int32_t GPS_filtered[2];
static int32_t GPS_degree[2]; //the lat lon degree without any decimals (lat/10 000 000)
static uint16_t fraction3[2];
#endif
static int16_t nav_takeoff_bearing; // saves the bearing at takeof (1deg = 1) used to rotate to takeoff direction when arrives at home
//Main navigation processor and state engine
// TODO: add proceesing states to ease processing burden
bool GPS_Compute(void) {
unsigned char axis;
uint32_t dist; //temp variable to store dist to copter
int32_t dir; //temp variable to store dir to copter
//check that we have a valid frame, if not then return immediatly
if (GPS_Frame == 0) {
return false;
} else {
GPS_Frame = 0;
}
if (f.GPS_FIX && GPS_numSat >= 4) {
//check home position and set it if it was not set
#if !defined(DONT_RESET_HOME_AT_ARM)
if (!f.ARMED) {
f.GPS_FIX_HOME = 0;
}
#endif
if (!f.GPS_FIX_HOME && f.ARMED) {
GPS_reset_home_position();
}
#if defined(GPS_FILTERING) && (!defined(INS_PH_NAV_ON))
//Apply moving average filter to GPS data
//if (GPS_conf.filtering) {
GPS_filter_index = (GPS_filter_index + 1) % GPS_FILTER_VECTOR_LENGTH;
for (axis = 0; axis < 2; axis++) {
GPS_read[axis] = GPS_coord[axis]; //latest unfiltered data is in GPS_latitude and GPS_longitude
GPS_degree[axis] = GPS_read[axis] / 10000000; // get the degree to assure the sum fits to the int32_t
// How close we are to a degree line ? its the first three digits from the fractions of degree
// later we use it to Check if we are close to a degree line, if yes, disable averaging,
fraction3[axis] = (GPS_read[axis] - GPS_degree[axis] * 10000000) / 10000;
GPS_filter_sum[axis] -= GPS_filter[axis][GPS_filter_index];
GPS_filter[axis][GPS_filter_index] = GPS_read[axis] - (GPS_degree[axis] * 10000000);
GPS_filter_sum[axis] += GPS_filter[axis][GPS_filter_index];
GPS_filtered[axis] = GPS_filter_sum[axis] / GPS_FILTER_VECTOR_LENGTH + (GPS_degree[axis] * 10000000);
if (NAV_state == NAV_STATE_HOLD_INFINIT || NAV_state == NAV_STATE_HOLD_TIMED) { //we use gps averaging only in poshold mode...
if (fraction3[axis] > 1 && fraction3[axis] < 999)
GPS_coord[axis] = GPS_filtered[axis];
}
}
//}
#endif
//dTnav calculation
//Time for calculating x,y speed and navigation pids
static uint32_t prevNavTime;
uint32_t currTime = millis();
dTnav = MS2S(currTime - prevNavTime);
prevNavTime = currTime;
//debug[1] = dTnav * 1000;
// prevent runup from bad GPS
dTnav = min(dTnav, 1.0);
//calculate distance and bearings for gui and other stuff continously - From home to copter
GPS_bearing(&GPS_coord[LAT], &GPS_coord[LON], &GPS_home[LAT], &GPS_home[LON], &dir);
GPS_directionToHome = dir / 100;
//GPS_distance_cm(&GPS_coord[LAT], &GPS_coord[LON], &GPS_home[LAT], &GPS_home[LON], &dist);
calculateDistanceToHome(&dist);
GPS_distanceToHome = dist / 100;
if (!f.GPS_FIX_HOME) { //If we don't have home set, do not display anything
GPS_distanceToHome = 0;
GPS_directionToHome = 0;
}
// Check fence setting and execute RTH if necessary
if ((GPS_conf.fence > 0) && (GPS_conf.fence < GPS_distanceToHome) && (f.GPS_mode != GPS_MODE_RTH)) {
mission_step.parameter1 = 1; // make auto landing after RTH
init_RTH();
}
//calculate the current velocity based on gps coordinates continously to get a valid speed at the moment when we start navigating
GPS_calc_velocity();
//Navigation state engine
if (f.GPS_mode != GPS_MODE_NONE) { //ok we are navigating ###0002
//do gps nav calculations here, these are common for nav and poshold
GPS_bearing(&GPS_coord[LAT], &GPS_coord[LON], &GPS_WP[LAT], &GPS_WP[LON], &target_bearing);
GPS_distance_cm(&GPS_coord[LAT], &GPS_coord[LON], &GPS_WP[LAT], &GPS_WP[LON], &wp_distance);
#ifndef INS_PH_NAV_ON
GPS_calc_location_error(&GPS_WP[LAT], &GPS_WP[LON], &GPS_coord[LAT], &GPS_coord[LON]);
#endif
int16_t speed = 0; //Desired navigation speed
switch (NAV_state) { //Navigation state machine
case NAV_STATE_NONE: //Just for clarity, do nothing when nav_state is none
break;
case NAV_STATE_LAND_START:
f.GPS_BARO_MODE = true; //Take control of BARO mode
f.LAND_COMPLETED = false;
setAltToHold(alt.estAlt);
#ifndef INS_PH_NAV_ON
applyPosHoldPIDControl(&dTnav); //Land in position hold
nav_timer_stop = millis() + 1000; // currTime + 1s
#else
nav_timer_stop = millis() + 100; // currTime + 100ms
#endif
NAV_state = NAV_STATE_LAND_SETTLE;
break;
case NAV_STATE_LAND_SETTLE:
#ifndef INS_PH_NAV_ON
applyPosHoldPIDControl(&dTnav);
#endif
if (millis() >= nav_timer_stop) {
f.LAND_IN_PROGRESS = true; // Flag land process
NAV_state = NAV_STATE_LAND_IN_PROGRESS;
}
break;
case NAV_STATE_LAND_IN_PROGRESS:
#ifndef INS_PH_NAV_ON
applyPosHoldPIDControl(&dTnav); //Land in position hold
#endif
if (isLanded()) {
//nav_timer_stop = millis() + 2000; // currTime + 2s
NAV_state = NAV_STATE_LANDED;
} else if(isGroundDetected()) { // if ground detected switch off position hold
NAV_state = NAV_STATE_LAND_DETECTED;
}
break;
case NAV_STATE_LAND_DETECTED:
if (isLanded()) {
//nav_timer_stop = millis() + 2000; // currTime + 2s
NAV_state = NAV_STATE_LANDED;
}
break;
case NAV_STATE_LANDED:
// Disarm if THROTTLE stick is at minimum or 2sec past after land detected
//if (rcData[THROTTLE] < MINCHECK || millis() >= nav_timer_stop) { // Throttle at minimum or 5sec passed.
go_disarm();
f.OK_TO_ARM = 0; //Prevent re-arming
f.GPS_BARO_MODE = false;
f.LAND_IN_PROGRESS = false;
f.LAND_COMPLETED = true;
GPS_reset_nav();
//}
break;
case NAV_STATE_HOLD_INFINIT: //Constant position hold, no timer. Only an rcOption change can exit from this
#ifndef INS_PH_NAV_ON
applyPosHoldPIDControl(&dTnav);
#endif
break;
case NAV_STATE_HOLD_TIMED:
if (nav_timer_stop == 0) { //We are start a timed poshold
nav_timer_stop = millis() + 1000 * nav_hold_time; //Set when we will continue
} else if (nav_timer_stop <= millis()) { //did we reach our time limit ?
if (mission_step.flag != MISSION_FLAG_END) {
NAV_state = NAV_STATE_PROCESS_NEXT; //if yes then process next mission step
}
NAV_error = NAV_ERROR_TIMEWAIT;
}
#ifndef INS_PH_NAV_ON
applyPosHoldPIDControl(&dTnav); //BTW hold position till next command
#endif
break;
case NAV_STATE_RTH_START:
if (GPS_distanceToHome <= RTH_RADIUS) {
if (mission_step.parameter1 == 0) {
setAltToHold(alt.estAlt); // just keep current alt in case of drone in RTH_RADIUS at RTH activation
NAV_state = NAV_STATE_HOLD_INFINIT;
} else {
NAV_state = NAV_STATE_LAND_START; // if parameter 1 in RTH step is non 0 then land at home
}
if (GPS_conf.nav_rth_takeoff_heading) {
magHold = nav_takeoff_bearing;
}
} else if (isAltitudeReached() || (!GPS_conf.wait_for_target_alt)) { //Wait until we reach RTH altitude
GPS_set_next_wp(&GPS_home[LAT], &GPS_home[LON], &GPS_coord[LAT], &GPS_coord[LON]); //If we reached then change mode and start RTH
NAV_state = NAV_STATE_RTH_ENROUTE;
NAV_error = NAV_ERROR_NONE;
} else {
NAV_error = NAV_ERROR_WAIT_FOR_TARGET_ALT;
}
#ifndef INS_PH_NAV_ON
applyPosHoldPIDControl(&dTnav); //hold position till we reach RTH alt
#endif
break;
case NAV_STATE_RTH_ENROUTE: //Doing RTH navigation
speed = GPS_calc_desired_speed(GPS_conf.nav_speed_max, GPS_conf.slow_nav);
GPS_calc_nav_rate(speed);
GPS_adjust_heading();
if ((wp_distance <= GPS_conf.wp_radius) || check_missed_wp()) { //if yes switch to poshold mode
if (mission_step.parameter1 == 0) {
NAV_state = NAV_STATE_HOLD_INFINIT;
} else {
NAV_state = NAV_STATE_LAND_START; // if parameter 1 in RTH step is non 0 then land at home
}
if (GPS_conf.nav_rth_takeoff_heading) {
magHold = nav_takeoff_bearing;
}
}
break;
case NAV_STATE_WP_START:
if (isAltitudeReached() || (!GPS_conf.wait_for_target_alt)) { //Wait until we reach WP altitude
GPS_set_next_wp(&mission_step.pos[LAT], &mission_step.pos[LON], &GPS_coord[LAT], &GPS_coord[LON]);
NAV_state = NAV_STATE_WP_ENROUTE;
NAV_error = NAV_ERROR_NONE;
} else {
NAV_error = NAV_ERROR_WAIT_FOR_TARGET_ALT;
}
#ifndef INS_PH_NAV_ON
applyPosHoldPIDControl(&dTnav); //hold position till we reach WP altitude
#endif
break;
case NAV_STATE_WP_ENROUTE:
speed = GPS_calc_desired_speed(GPS_conf.nav_speed_max, GPS_conf.slow_nav);
GPS_calc_nav_rate(speed);
GPS_adjust_heading();
if ((wp_distance <= GPS_conf.wp_radius) || check_missed_wp()) { //This decides what happen when we reached the WP coordinates
if (mission_step.action == MISSION_LAND) { //Autoland
NAV_state = NAV_STATE_LAND_START; //Start landing
} else if (mission_step.flag == MISSION_FLAG_END) { //If this was the last mission step (flag set by the mission planner), then switch to poshold
NAV_state = NAV_STATE_HOLD_INFINIT;
NAV_error = NAV_ERROR_FINISH;
} else if (mission_step.action == MISSION_HOLD_UNLIM) { //If mission_step was POSHOLD_UNLIM and we reached the position then switch to poshold unlimited
NAV_state = NAV_STATE_HOLD_INFINIT;
NAV_error = NAV_ERROR_FINISH;
} else if (mission_step.action == MISSION_HOLD_TIME) { //If mission_step was a timed poshold then initiate timed poshold
nav_hold_time = mission_step.parameter1;
nav_timer_stop = 0; //This indicates that we are starting a timed poshold
NAV_state = NAV_STATE_HOLD_TIMED;
} else {
NAV_state = NAV_STATE_PROCESS_NEXT; //Otherwise process next step
}
}
break;
case NAV_STATE_DO_JUMP:
if (jump_times < 0) { //Jump unconditionally (supposed to be -1) -10 should not be here
next_step = mission_step.parameter1;
NAV_state = NAV_STATE_PROCESS_NEXT;
}
if (jump_times == 0) {
jump_times = -10; //reset jump counter
if (mission_step.flag == MISSION_FLAG_END) { //If this was the last mission step (flag set by the mission planner), then switch to poshold
NAV_state = NAV_STATE_HOLD_INFINIT;
NAV_error = NAV_ERROR_FINISH;
} else
NAV_state = NAV_STATE_PROCESS_NEXT;
}
if (jump_times > 0) { //if zero not reached do a jump
next_step = mission_step.parameter1;
NAV_state = NAV_STATE_PROCESS_NEXT;
jump_times--;
}
break;
case NAV_STATE_PROCESS_NEXT: //Processing next mission step
NAV_error = NAV_ERROR_NONE;
if (!recallWP(next_step)) {
abort_mission(NAV_ERROR_WP_CRC);
} else {
switch (mission_step.action) {
//Waypoint and hold commands all starts with an enroute status it includes the LAND command too
case MISSION_WAYPOINT:
case MISSION_HOLD_TIME:
case MISSION_HOLD_UNLIM:
case MISSION_LAND:
setAltToHold(mission_step.altitude);
// all WP starts with a position hold. This allows to go to WP altitude.
predictAndSetPositionToHold(); // predict and set point to hold
if ((wp_distance / 100) >= GPS_conf.safe_wp_distance) {
abort_mission(NAV_ERROR_TOOFAR);
} else {
NAV_state = NAV_STATE_WP_START;
}
//GPS_prev[LAT] = mission_step.pos[LAT]; //Save wp coordinates for precise route calc
//GPS_prev[LON] = mission_step.pos[LON];
break;
case MISSION_RTH:
f.GPS_head_set = 0;
if (GPS_conf.rth_altitude == 0 && mission_step.altitude == 0) { //if config and mission_step alt is zero
setAltToHold(alt.estAlt); // RTH returns at the actual altitude
} else {
uint32_t rth_alt;
if (mission_step.altitude == 0) {
rth_alt = GPS_conf.rth_altitude * 100; //altitude in mission step has priority
} else {
rth_alt = mission_step.altitude;
}
if (alt.estAlt < rth_alt) {
setAltToHold(rth_alt); //BUt only if we are below it.
} else {
setAltToHold(alt.estAlt);
}
}
// all RTH starts with a position hold. This allows to go to RTH altitude.
predictAndSetPositionToHold(); // predict and set point to hold
NAV_state = NAV_STATE_RTH_START;
break;
case MISSION_JUMP:
if (jump_times == -10)
jump_times = mission_step.parameter2;
if (mission_step.parameter1 > 0 && mission_step.parameter1 < mission_step.number)
NAV_state = NAV_STATE_DO_JUMP;
else
//Error situation, invalid jump target
abort_mission(NAV_ERROR_INVALID_JUMP);
break;
case MISSION_SET_HEADING:
GPS_poi[LAT] = 0;
GPS_poi[LON] = 0; // zeroing this out clears the possible previous set_poi
if (mission_step.parameter1 < 0)
f.GPS_head_set = 0;
else {
f.GPS_head_set = 1;
GPS_directionToPoi = mission_step.parameter1;
}
break;
case MISSION_SET_POI:
GPS_poi[LAT] = mission_step.pos[LAT];
GPS_poi[LON] = mission_step.pos[LON];
f.GPS_head_set = 1;
break;
default: //if we got an unknown action code abort mission and hold position
abort_mission(NAV_ERROR_INVALID_DATA);
break;
}
next_step++; //Prepare for the next step
}
break;
} // switch end
} //end of gps calcs ###0002
}
return true;
} // End of GPS_compute
// Abort current mission with the given error code (switch to poshold_infinit)
void abort_mission(unsigned char error_code) {
GPS_set_next_wp(&GPS_coord[LAT], &GPS_coord[LON], &GPS_coord[LAT], &GPS_coord[LON]);
NAV_error = error_code;
NAV_state = NAV_STATE_HOLD_INFINIT;
}
//Adjusting heading according to settings - MAG mode must be enabled
void GPS_adjust_heading() {
//TODO: Add slow windup for large heading change
//This controls the heading
if (f.GPS_head_set) { // We have seen a SET_POI or a SET_HEADING command
if (GPS_poi[LAT] == 0)
magHold = wrap_18000((GPS_directionToPoi * 100)) / 100;
else {
GPS_bearing(&GPS_coord[LAT], &GPS_coord[LON], &GPS_poi[LAT], &GPS_poi[LON], &GPS_directionToPoi);
GPS_distance_cm(&GPS_coord[LAT], &GPS_coord[LON], &GPS_poi[LAT], &GPS_poi[LON], &wp_distance);
magHold = GPS_directionToPoi / 100;
}
} else { // heading controlled by the standard defines
if (GPS_conf.nav_controls_heading) {
if (GPS_conf.nav_tail_first) {
magHold = wrap_18000(target_bearing - 18000) / 100;
} else {
magHold = wrap_18000(target_bearing) / 100;
}
}
}
}
////////////////////////////////////////////////////////////////////////////////////
//PID based GPS navigation functions
//Author : EOSBandi
//Based on code and ideas from the Arducopter team: Jason Short,Randy Mackay, Pat Hickey, Jose Julio, Jani Hirvinen
//Andrew Tridgell, Justin Beech, Adam Rivera, Jean-Louis Naudin, Roberto Navoni
//original constraint does not work with variables
int16_t constrain_int16(int16_t amt, int16_t low, int16_t high) {
return ((amt) < (low) ? (low) : ((amt) > (high) ? (high) : (amt)));
}
////////////////////////////////////////////////////////////////////////////////////
// this is used to offset the shrinking longitude as we go towards the poles
// It's ok to calculate this once per waypoint setting, since it changes a little within the reach of a multicopter
//
void GPS_calc_longitude_scaling(int32_t lat) {
GPS_scaleLonDown = cos(lat * 1.0e-7f * 0.01745329251f);
}
////////////////////////////////////////////////////////////////////////////////////
// Sets the waypoint to navigate, reset neccessary variables and calculate initial values
//
void GPS_set_next_wp(int32_t* lat_to, int32_t* lon_to, int32_t* lat_from, int32_t* lon_from) {
GPS_WP[LAT] = *lat_to;
GPS_WP[LON] = *lon_to;
GPS_FROM[LAT] = *lat_from;
GPS_FROM[LON] = *lon_from;
GPS_calc_longitude_scaling(*lat_to);
GPS_bearing(&GPS_FROM[LAT], &GPS_FROM[LON], &GPS_WP[LAT], &GPS_WP[LON], &target_bearing);
GPS_distance_cm(&GPS_FROM[LAT], &GPS_FROM[LON], &GPS_WP[LAT], &GPS_WP[LON], &wp_distance);
#ifdef INS_PH_NAV_ON
positionToHold[LAT] = (GPS_WP[LAT] - GPS_home[LAT]) * LAT_LON_TO_CM;
positionToHold[LON] = (GPS_WP[LON] - GPS_home[LON]) * LAT_LON_TO_CM * GPS_scaleLonDown;
#else
GPS_calc_location_error(&GPS_WP[LAT], &GPS_WP[LON], &GPS_FROM[LAT], &GPS_FROM[LON]);
#endif
waypoint_speed_gov = GPS_conf.nav_speed_min;
original_target_bearing = target_bearing;
}
////////////////////////////////////////////////////////////////////////////////////
// Check if we missed the destination somehow
//
static bool check_missed_wp(void) {
int32_t temp;
temp = target_bearing - original_target_bearing;
temp = wrap_18000(temp);
return (abs(temp) > 10000); // we passed the waypoint by 100 degrees
}
////////////////////////////////////////////////////////////////////////////////////
// Get distance between two points in cm
// Get bearing from pos1 to pos2, returns an 1deg = 100 precision
void GPS_bearing(int32_t* lat1, int32_t* lon1, int32_t* lat2, int32_t* lon2, int32_t* bearing) {
int32_t off_x = *lon2 - *lon1;
int32_t off_y = (*lat2 - *lat1) / GPS_scaleLonDown;
*bearing = 9000 + atan2(-off_y, off_x) * 5729.57795f; //Convert the output redians to 100xdeg
if (*bearing < 0) *bearing += 36000;
}
void GPS_distance_cm(int32_t* lat1, int32_t* lon1, int32_t* lat2, int32_t* lon2, uint32_t* dist) {
float dLat = (float) (*lat1 - *lat2); // difference of latitude in 1/10 000 000 degrees
float dLon = (float) (*lon1 - *lon2) * GPS_scaleLonDown; //x
*dist = sqrt(sq(dLat) + sq(dLon)) * LAT_LON_TO_CM;
}
void calculateDistanceToHome(uint32_t* dist) {
gpsDistanceToHome[LAT] = (GPS_coord[LAT] - GPS_home[LAT]) * LAT_LON_TO_CM;
gpsDistanceToHome[LON] = (GPS_coord[LON] - GPS_home[LON]) * LAT_LON_TO_CM * GPS_scaleLonDown; //x
*dist = sqrt(sq((float)gpsDistanceToHome[LAT]) + sq((float)gpsDistanceToHome[LON]));
}
//*******************************************************************************************************
// calc_velocity_and_filtered_position - velocity in lon and lat directions calculated from GPS position
// and accelerometer data
// lon_speed expressed in cm/s. positive numbers mean moving east
// lat_speed expressed in cm/s. positive numbers when moving north
// Note: we use gps locations directly to calculate velocity instead of asking gps for velocity because
// this is more accurate below 1.5m/s
//*******************************************************************************************************
static void GPS_calc_velocity(void) {
static int16_t speed_old[2] = { 0, 0 };
static int32_t last[2] = { 0, 0 };
static uint8_t init = 0;
if (init) {
// normalize GPS delta time for speed calculation (normalized time should not be used in PID controllers)
#define JITTER_DT 0.03f
float tmp;
if (dTnav >= (HZ2S(10)-JITTER_DT) && dTnav <= (HZ2S(10)+JITTER_DT)) {
tmp = HZ2S(10); // 10Hz Data 100ms
} else if (dTnav >= (HZ2S(5)-JITTER_DT) && dTnav <= (HZ2S(5)+JITTER_DT)) {
tmp = HZ2S(5); // 5Hz Data 200ms
} else {
tmp = dTnav;
}
//debug[2] = tmp * 1000;
tmp = 1.0 / tmp;
gpsActualSpeed[_X] = (float) (GPS_coord[LON] - last[LON]) * GPS_scaleLonDown * tmp;
gpsActualSpeed[_Y] = (float) (GPS_coord[LAT] - last[LAT]) * tmp;
//TODO: Check unrealistic speed changes and signal navigation about possible gps signal degradation
gpsActualSpeed[_X] = (gpsActualSpeed[_X] + speed_old[_X]) / 2;
gpsActualSpeed[_Y] = (gpsActualSpeed[_Y] + speed_old[_Y]) / 2;
speed_old[_X] = gpsActualSpeed[_X];
speed_old[_Y] = gpsActualSpeed[_Y];
//GPS_speed = 1.0f/InvSqrt( sq((int32_t)gpsActualSpeed[LAT]) + sq((int32_t)gpsActualSpeed[LON]) );
}
init = 1;
last[LON] = GPS_coord[LON];
last[LAT] = GPS_coord[LAT];
}
float getPredictedDeltaToStop(float *velocity) {
//float timeToPredictPointInPH = conf.pid[PIDPOS].I8/100.0f;
float tmp = (*velocity / 100.0f) * posholdPID_PARAM.kI;
tmp = (tmp > 0) ? (tmp * tmp) : -(tmp * tmp);
tmp = constrain(tmp, -15.0f, 15.0f); // in cm, i.e. +/-15 meters
return tmp * 100.0f; // to cm
}
void predictAndSetPositionToHold() {
#ifdef INS_PH_NAV_ON
//float timeToPredictPointInPH = conf.pid[PIDPOS].I8/100.0f;
#ifdef DISABLE_INS_WHEN_PH_OFF
positionToHold[LAT] = gpsDistanceToHome[LAT] + gpsActualSpeed[LAT] * posholdPID_PARAM.kI;
positionToHold[LON] = gpsDistanceToHome[LON] + gpsActualSpeed[LON] * posholdPID_PARAM.kI;
#else
//positionToHold[LAT] = ins.positionEF[LAT] + getPredictedDeltaToStop(&ins.velocityEF[LAT]);
//positionToHold[LON] = ins.positionEF[LON] + getPredictedDeltaToStop(&ins.velocityEF[LON]);
positionToHold[LAT] = ins.positionEF[LAT] + ins.velocityEF[LAT] * posholdPID_PARAM.kI;
positionToHold[LON] = ins.positionEF[LON] + ins.velocityEF[LON] * posholdPID_PARAM.kI;
#endif
GPS_hold[LAT] = GPS_home[LAT] + positionToHold[LAT]/LAT_LON_TO_CM;
GPS_hold[LON] = GPS_home[LON] + positionToHold[LON]/(LAT_LON_TO_CM * GPS_scaleLonDown);
#else
GPS_hold[LAT] = GPS_coord[LAT] + gpsActualSpeed[LAT] * posholdPID_PARAM.kI;
GPS_hold[LON] = GPS_coord[LON] + ((gpsActualSpeed[LON] * posholdPID_PARAM.kI) / GPS_scaleLonDown);
GPS_set_next_wp(&GPS_hold[LAT], &GPS_hold[LON], &GPS_hold[LAT], &GPS_hold[LON]); // hold at the predicted position
#endif
}
#ifndef INS_PH_NAV_ON
////////////////////////////////////////////////////////////////////////////////////
// Calculate a location error between two gps coordinates
// Because we are using lat and lon to do our distance errors here's a quick chart:
// 100 = 1m
// 1000 = 11m = 36 feet
// 1800 = 19.80m = 60 feet
// 3000 = 33m
// 10000 = 111m
//
static void GPS_calc_location_error(int32_t* target_lat, int32_t* target_lng, int32_t* gps_lat, int32_t* gps_lng) {
gpsPositionError[LON] = (float) (*target_lng - *gps_lng) * GPS_scaleLonDown; // X Error
gpsPositionError[LAT] = *target_lat - *gps_lat; // Y Error
}
// TODO: check that the poshold target speed constraint can be increased for snappier poshold lock
static void applyGPSPosHoldPIDControl(float* dt) {
int32_t d;
int32_t target_speed;
uint8_t axis;
for (axis = 0; axis < 2; axis++) {
target_speed = get_P(gpsPositionError[axis], &posholdPID_PARAM); // calculate desired speed from lat/lon error
target_speed = constrain(target_speed, -100, 100); // Constrain the target speed in poshold mode to 1m/s it helps avoid runaways..
rate_error[axis] = target_speed - gpsActualSpeed[axis]; // calc the speed error
nav[axis] =
get_P(rate_error[axis], &poshold_ratePID_PARAM)
+ get_I(rate_error[axis] + gpsPositionError[axis], dt, &poshold_ratePID[axis], &poshold_ratePID_PARAM);
d = get_D(gpsPositionError[axis], dt, &poshold_ratePID[axis], &poshold_ratePID_PARAM);
d = constrain(d, -2000, 2000);
// get rid of noise
if(abs(gpsActualSpeed[axis]) < 50) d = 0;
nav[axis] += d;
// nav[axis] = constrain(nav[axis], -NAV_BANK_MAX, NAV_BANK_MAX);
nav[axis] = constrain_int16(nav[axis], -GPS_conf.nav_bank_max, GPS_conf.nav_bank_max);
navPID[axis].integrator = poshold_ratePID[axis].integrator;
}
}
#else
static void applyINSPosHoldPIDControl(float* dt) {
int32_t target[2];
uint8_t axis;
for (axis = 0; axis < 2; axis++) {
int32_t positionError = positionToHold[axis] - ins.positionEF[axis];
int32_t targetSpeed = get_P(positionError, &posholdPID_PARAM); // calculate desired speed from lat/lon ins error
targetSpeed = constrain(targetSpeed, -1000, 1000); // Constrain the target speed in position hold mode to 10m/s
int32_t rateError = targetSpeed - ins.velocityEF[axis]; // calculate the speed error
rateError = constrain(rateError, -1000, 1000);
nav[axis] = get_P(rateError, &poshold_ratePID_PARAM) +
get_I(rateError, dt, &poshold_ratePID[axis], &poshold_ratePID_PARAM);
// rate D-part
nav[axis] -= constrain_int16((ins.accelEF_Filtered[axis] * poshold_ratePID_PARAM.kD), -2000, 2000);
//nav[axis] = constrain(nav[axis], -NAV_BANK_MAX, NAV_BANK_MAX);
nav[axis] = constrain_int16(nav[axis], -GPS_conf.nav_bank_max, GPS_conf.nav_bank_max);
navPID[axis].integrator = poshold_ratePID[axis].integrator;
}
}
#endif
void applyPosHoldPIDControl(float* dt) {
// to avoid turnover, position hold have to be off when ground detected or takeoff,
// because gps coordinate can be changed during the land detection
if(!isTakeOffInProgress() && !isGroundDetectedFor100ms()) {
#ifdef INS_PH_NAV_ON
applyINSPosHoldPIDControl(dt);
#else
applyGPSPosHoldPIDControl(dt);
#endif
} else {
for (uint8_t i = 0; i < 2; i++) {
nav[i] = 0;
#ifndef INS_PH_NAV_ON
nav_rated[i] = 0;
#endif
reset_PID(&poshold_ratePID[i]);
}
}
}
bool isNavStateForPosHold() {
return NAV_state == NAV_STATE_LAND_START
|| NAV_state == NAV_STATE_LAND_SETTLE
|| NAV_state == NAV_STATE_LAND_IN_PROGRESS
|| NAV_state == NAV_STATE_HOLD_INFINIT
|| NAV_state == NAV_STATE_HOLD_TIMED
|| NAV_state == NAV_STATE_RTH_START
|| NAV_state == NAV_STATE_WP_START;
}
////////////////////////////////////////////////////////////////////////////////////
// Calculate the desired nav_lat and nav_lon for distance flying such as RTH and WP
//
static void GPS_calc_nav_rate(uint16_t max_speed) {
float trig[2];
int32_t target_speed[2];
int32_t tilt;
uint8_t axis;
GPS_update_crosstrack();
int16_t cross_speed = crosstrack_error * (GPS_conf.crosstrack_gain / 100.0); //check is it ok ?
cross_speed = constrain(cross_speed, -200, 200);
cross_speed = -cross_speed;
float temp = (9000l - target_bearing) * RADX100;
trig[_X] = cos(temp);
trig[_Y] = sin(temp);
target_speed[_X] = max_speed * trig[_X] - cross_speed * trig[_Y];
target_speed[_Y] = cross_speed * trig[_X] + max_speed * trig[_Y];
for (axis = 0; axis < 2; axis++) {
rate_error[axis] = target_speed[axis] - gpsActualSpeed[axis];
rate_error[axis] = constrain(rate_error[axis], -1000, 1000);
nav[axis] =
get_P(rate_error[axis], &navPID_PARAM)
+get_I(rate_error[axis], &dTnav, &navPID[axis], &navPID_PARAM)
+ get_D(rate_error[axis], &dTnav, &navPID[axis], &navPID_PARAM);
// nav[axis] = constrain(nav[axis],-NAV_BANK_MAX,NAV_BANK_MAX);
nav[axis] = constrain_int16(nav[axis], -GPS_conf.nav_bank_max, GPS_conf.nav_bank_max);
poshold_ratePID[axis].integrator = navPID[axis].integrator;
}
}
static void GPS_update_crosstrack(void) {
// Crosstrack Error
// ----------------
// If we are too far off or too close we don't do track following
float temp = (target_bearing - original_target_bearing) * RADX100;
crosstrack_error = sin(temp) * wp_distance; // Meters we are off track line
}
////////////////////////////////////////////////////////////////////////////////////
// Determine desired speed when navigating towards a waypoint, also implement slow
// speed rampup when starting a navigation
//
// |< WP Radius
// 0 1 2 3 4 5 6 7 8m
// ...|...|...|...|...|...|...|...|
// 100 | 200 300 400cm/s
// | +|+
// |< we should slow to 1 m/s as we hit the target
//
static uint16_t GPS_calc_desired_speed(uint16_t max_speed, bool _slow) {
if (_slow) {
max_speed = min(max_speed, wp_distance / 2);
} else {
max_speed = min(max_speed, wp_distance);
max_speed = max(max_speed, GPS_conf.nav_speed_min); // go at least nav_speed_min
}
// limit the ramp up of the speed
// waypoint_speed_gov is reset to 0 at each new WP command
if (max_speed > waypoint_speed_gov) {
waypoint_speed_gov += (int) (100.0 * dTnav); // increase at .5/ms
max_speed = waypoint_speed_gov;
}
return max_speed;
}
////////////////////////////////////////////////////////////////////////////////////
// Utilities
//
int32_t wrap_36000(int32_t ang) {
if (ang > 36000) ang -= 36000;
if (ang < 0) ang += 36000;
return ang;
}
/*
* EOS increased the precision here, even if we think that the gps is not precise enough, with 10e5 precision it has 76cm resolution
* with 10e7 it's around 1 cm now. Increasing it further is irrelevant, since even 1cm resolution is unrealistic, however increased
* resolution also increased precision of nav calculations
*/
#define DIGIT_TO_VAL(_x) (_x - '0')
uint32_t GPS_coord_to_degrees(char* s) {
char *p, *q;
uint8_t deg = 0, min = 0;
unsigned int frac_min = 0;
uint8_t i;
// scan for decimal point or end of field
for (p = s; isdigit(*p); p++) ;
q = s;
// convert degrees
while ((p - q) > 2) {
if (deg)
deg *= 10;
deg += DIGIT_TO_VAL(*q++);
}
// convert minutes
while (p > q) {
if (min)
min *= 10;
min += DIGIT_TO_VAL(*q++);
}
// convert fractional minutes
// expect up to four digits, result is in
// ten-thousandths of a minute
if (*p == '.') {
q = p + 1;
for (i = 0; i < 4; i++) {
frac_min *= 10;
if (isdigit(*q))
frac_min += *q++ - '0';
}
}
return deg * 10000000UL + (min * 1000000UL + frac_min * 100UL) / 6;
}
// helper functions
uint16_t grab_fields(char* src, uint8_t mult) { // convert string to uint16
uint8_t i;
uint16_t tmp = 0;
for (i = 0; src[i] != 0; i++) {
if (src[i] == '.') {
i++;
if (mult == 0)
break;
else
src[i + mult] = 0;
}
tmp *= 10;
if (src[i] >= '0' && src[i] <= '9')
tmp += src[i] - '0';
}
return tmp;
}
uint8_t hex_c(uint8_t n) { // convert '0'..'9','A'..'F' to 0..15
n -= '0';
if(n>9) n -= 7;
n &= 0x0F;
return n;
}
//************************************************************************
// Common GPS functions
//
void init_RTH() {
f.GPS_mode = GPS_MODE_RTH; // Set GPS_mode to RTH
f.GPS_BARO_MODE = true;
NAV_paused_at = 0;
if (GPS_conf.rth_altitude == 0) {
setAltToHold(alt.estAlt); //Return at actual altitude
} else {
// RTH altitude is defined, but we use it only if we are below it
if (alt.estAlt < GPS_conf.rth_altitude * 100) {
setAltToHold(GPS_conf.rth_altitude * 100);
} else {
setAltToHold(alt.estAlt);
}
}
f.GPS_head_set = 0; //Allow the RTH ti handle heading
// all RTH starts with a position hold. This allows to go to RTH altitude.
predictAndSetPositionToHold(); // predict and set point to hold
NAV_state = NAV_STATE_RTH_START; //NAV engine status is Starting RTH.
}
void GPS_reset_home_position(void) {
if (f.GPS_FIX && GPS_numSat >= 5) {
GPS_home[LAT] = GPS_coord[LAT];
GPS_home[LON] = GPS_coord[LON];
GPS_calc_longitude_scaling(GPS_coord[LAT]); //need an initial value for distance and bearing calc
nav_takeoff_bearing = att.heading; //save takeoff heading
//TODO: Set ground altitude
f.GPS_FIX_HOME = 1;
}
}
//reset navigation (stop the navigation processor, and clear nav)
void GPS_reset_nav(void) {
uint8_t i;
for (i = 0; i < 2; i++) {
nav[i] = 0;
#ifndef INS_PH_NAV_ON
nav_rated[i] = 0;
#endif
reset_PID(&posholdPID[i]);
reset_PID(&poshold_ratePID[i]);