-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
2567 lines (2276 loc) · 84.9 KB
/
Copy pathmain.cpp
File metadata and controls
2567 lines (2276 loc) · 84.9 KB
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
/* BEGIN INCLUDE SYSTEM LIBRARIES */
#include <Arduino.h> // Arduino Framework
#include <lib_xcore>
#include <xcore/math_module>
#include <File_Utility.h> // File Utility
#include <LibAvionics.h> // Base Avionics Library and Utilities
#include "SystemFunctions.h" // Function Declarations
#include "custom_kalman.h" // Kalman Quick Table
#if __has_include("STM32FreeRTOS.h")
# define USE_FREERTOS 1
# include "hal_rtos.h"
#endif
// Hardware
#include <STM32SD.h>
#include <STM32LowPower.h>
#include <Adafruit_NeoPixel.h>
#include "SparkFun_BNO08x_Arduino_Library.h"
#include <INA236.h>
#include "SparkFun_VL53L1X.h"
#include <Servo.h>
#include <XBee.h>
/* BEGIN INCLUDE USER'S IMPLEMENTATIONS */
#include "config/Main/UserConfig.h"
#include "UserPins.h" // User's Pins Mapping
#include "UserSensors.h" // User's Hardware Implementations
#include "UserFSM.h" // User's FSM States
#include "Controlling.h"
#include "custom_EEPROM.h"
#include "BNO086Cal.h"
#include "XBeeDriver.h"
/* END INCLUDE USER'S IMPLEMENTATIONS */
/* BEGIN INCLUDE MAIN */
#include "./main.h"
/* END INCLUDE MAIN */
/* BEGIN SENSOR INSTANCES */
TwoWire i2c4(USER_GPIO_I2C4_SDA, USER_GPIO_I2C4_SCL);
HardwareSerial ServoSerial(USER_GPIO_Half);
HardwareSerial XbeeSerial(USER_GPIO_XBEE_RX, USER_GPIO_XBEE_TX);
XBee xbee;
SFE_UBLOX_GNSS m10s;
INA236 ina(0x40, &i2c4);
sh2_SensorValue_t sensorValue;
// SFEVL53L1X tof(i2c4);
BNO08x bno;
BNO086Calibrator bno_cal;
Adafruit_NeoPixel led(2, USER_GPIO_LED, NEO_GRB + NEO_KHZ800);
Servo servo_a;
Servo servo_b;
SensorIMU *imu[RA_NUM_IMU] = {
new IMU_ISM256(USER_GPIO_ISM256_NSS), // IMU #1
};
SensorAltimeter *altimeter[RA_NUM_ALTIMETER] = {
new Altimeter_BMP581(USER_GPIO_BMP581_NSS), // Altimeter #1 — SPI
new Altimeter_MS5611(MS5611_ADDR, i2c4), // Altimeter #2 — I2C
};
/* END SENSOR INSTANCES */
/* BEGIN SENSOR STATUSES */
struct SensorsHealth {
SensorStatus imu[RA_NUM_IMU]{};
SensorStatus altimeter[RA_NUM_ALTIMETER]{};
SensorStatus gnss[RA_NUM_GNSS]{};
} sensors_health;
/* END SENSOR STATUSES */
/* BEGIN PERSISTENT STATE */
UserFSM fsm;
double acc;
double alt_ref; // Altitude at ground
double alt_agl; // Altitude above ground
double apogee_raw;
uint32_t packet_count{};
// 0 = altimeter[0] (BMP581), 1 = altimeter[1] (MS5611), 2 = average of both
uint8_t altimeter_source = 0;
/* END PERSISTENT STATE */
/* BEGIN DATA MEMORY */
DataMemory data;
String sd_buf;
String tx_buf;
/* END DATA MEMORY */
/* Control*/
GPSCoordinate current_location;
Controller controller;
numeric_vector<3> servo_target_angles;
/* BEGIN ACTUATORS */
float pos_a = RA_SERVO_A_LOCK;
float pos_b = RA_SERVO_B_LOCK;
/* END ACTUATORS */
static inline void write_servo_a(float angle) {
servo_a.attach(USER_GPIO_SERVO_A, RA_SERVO_A_MIN, RA_SERVO_A_MAX, RA_SERVO_A_MAX);
servo_a.write(angle);
hal::rtos::delay_ms(100);
servo_a.detach();
}
static inline void write_servo_b(float angle) {
servo_b.attach(USER_GPIO_SERVO_B, RA_SERVO_B_MIN, RA_SERVO_B_MAX, RA_SERVO_B_MAX);
servo_b.write(angle);
hal::rtos::delay_ms(100);
servo_b.detach();
}
volatile bool ins_thresholds_dirty = false;
volatile bool apogee_alt_dirty = false;
/* EEPROM — backed by STM32H725 Backup SRAM (0x38800000)
Direct memcpy: no Flash erase, no blocking, ~microseconds.*/
void EEPROM_Write() {
EEPROMStore s{};
s.magic = EEPROM_MAGIC;
memcpy(s.utc, data.utc, sizeof(s.utc));
s.packet_count = packet_count;
s.alt_ref = alt_ref;
s.pos_a = pos_a;
s.pos_b = pos_b;
for (size_t i = 0; i < 3; ++i)
s.servo_angles[i] = controller.last_angles[i];
s.telemetry_en = telemetry_enabled ? 1u : 0u;
s.crc = eeprom_crc8(
reinterpret_cast<const uint8_t *>(&s) + EEPROM_PAYLOAD_OFFSET,
sizeof(EEPROMStore) - EEPROM_PAYLOAD_OFFSET);
memcpy(reinterpret_cast<void *>(BKPSRAM_BASE), &s, sizeof(s));
SCB_CleanDCache_by_Addr(reinterpret_cast<uint32_t *>(BKPSRAM_BASE), sizeof(EEPROMStore));
__DSB();
}
// Read only if magic + CRC are valid (data was previously *defined*).
// cold_boot=true (POR/BOR): only tuning params are restored; FSM state and
// BKPSRAM are skipped so the vehicle starts clean after a full power cycle.
// cold_boot=false (pin/button/watchdog reset): full restore.
void EEPROM_Read(bool cold_boot = false) {
if (cold_boot) return;
FlashConfig fc{};
const bool flash_valid = FLASH_Config_Read(fc);
if (flash_valid) {
fsm.transfer(static_cast<UserState>(fc.state));
fsm.on_enter(); // consume flag so EvalFSM doesn't re-trigger GPIO side-effects on boot
at = fc.bearing_ema_alpha;
at_ctrl = fc.ctrl_ema_alpha;
HEADING_DEADBAND_DEG = fc.heading_deadband_deg;
}
EEPROMStore s{};
memcpy(&s, reinterpret_cast<const void *>(BKPSRAM_BASE), sizeof(s));
if (s.magic != EEPROM_MAGIC) return;
const uint8_t expected = eeprom_crc8(
reinterpret_cast<const uint8_t *>(&s) + EEPROM_PAYLOAD_OFFSET,
sizeof(EEPROMStore) - EEPROM_PAYLOAD_OFFSET);
if (s.crc != expected) return;
memcpy(data.utc, s.utc, sizeof(data.utc));
packet_count = s.packet_count;
alt_ref = s.alt_ref;
pos_a = s.pos_a;
pos_b = s.pos_b;
for (size_t i = 0; i < 3; ++i)
controller.last_angles[i] = s.servo_angles[i];
telemetry_enabled = s.telemetry_en != 0u;
}
// Write flight state and guidance config to Flash (persists across full power loss).
void EEPROM_WriteGuidanceCfg() {
FlashConfig fc{};
fc.state = static_cast<uint8_t>(fsm.state());
fc.bearing_ema_alpha = at;
fc.ctrl_ema_alpha = at_ctrl;
fc.heading_deadband_deg = HEADING_DEADBAND_DEG;
FLASH_Config_Write(fc);
}
// FSM transition wrapper — transfers state then immediately persists to Flash.
static inline void fsm_transfer(UserState next) {
fsm.transfer(next);
EEPROM_WriteGuidanceCfg();
}
/* BEGIN SD CARD */
FsUtil fs_sd;
/* END SD CARD */
/* BEGIN FILTERS */
xcore::vdt<FILTER_ORDER - 1> vdt(static_cast<double>(RA_INTERVAL_FSM_EVAL) * 0.001);
FilterAcc filter_acc;
FilterAlt filter_alt;
FilterGPS filter_nav_n; // state[0]=lat_deg (filtered), state[1]=vn_m_s (filtered)
FilterGPS filter_nav_e; // state[0]=lon_deg (filtered), state[1]=ve_m_s (filtered)
/* END FILTERS */
/* BEGIN USER PRIVATE VARIABLES */
hal::rtos::mutex_t mtx_spi;
hal::rtos::mutex_t mtx_sdio;
hal::rtos::mutex_t mtx_i2c; // guards i2c4 bus (BNO, GPS, INA, TOF)
hal::rtos::mutex_t mtx_cdc;
hal::rtos::mutex_t mtx_uart;
hal::rtos::mutex_t mtx_buf; // guards tx_buf and sd_buf
hal::rtos::mutex_t mtx_nav; // guards nav_state — held for microseconds only
hal::rtos::mutex_t mtx_kf; // guards filter_acc, filter_alt, alt_agl, apogee_raw
/* BEGIN USER PRIVATE FUNCTIONS */
uint32_t LoggerInterval() {
switch (fsm.state()) {
case UserState::STARTUP:
case UserState::IDLE_SAFE:
return RA_SDLOGGER_INTERVAL_IDLE;
case UserState::LAUNCH_PAD:
return RA_SDLOGGER_INTERVAL_SLOW;
case UserState::ASCENT:
case UserState::APOGEE:
return RA_SDLOGGER_INTERVAL_REALTIME;
case UserState::DESCENT:
case UserState::PROBE_RELEASE:
case UserState::PAYLOAD_RELEASE:
return RA_SDLOGGER_INTERVAL_FAST;
case UserState::LANDED:
default:
return RA_SDLOGGER_INTERVAL_IDLE;
}
}
/* END USER PRIVATE FUNCTIONS */
// Navigation state written by GNSS/MAG tasks, read by CB_Control.
// Kept separate from mtx_i2c so CB_Control never blocks on an I2C transaction.
struct NavState {
GPSCoordinate location{};
double vn = 0;
double ve = 0;
double yaw = 0;
double heading = 0; // GPS ground-track heading (deg, North-relative) from getHeading()
bool fixed = false;
} nav_state;
// Kinematic sim — advanced by CB_Control each tick when simActivated is true.
// Walk from (13.723296, 100.515844) → (13.723175, 100.515373) at ~1.4 m/s with oscillating yaw.
namespace SimNav {
constexpr double START_LAT = 13.723296212428615;
constexpr double START_LON = 100.51584405033603;
constexpr double START_ALT = 100.0;
constexpr double DESCENT_RATE = 2.0;
// Walking velocity components toward end point (~1.4 m/s, heading ~255° SW)
constexpr double INIT_VN = -0.358; // m/s northward
constexpr double INIT_VE = -1.353; // m/s eastward
constexpr float YAW_AMP = 20.0f; // yaw oscillation amplitude ±20°
constexpr float YAW_FREQ = 1.5f; // oscillation frequency rad/s (~4 s period)
static double lat = START_LAT;
static double lon = START_LON;
static double alt = START_ALT;
static double vn = INIT_VN;
static double ve = INIT_VE;
static float yaw_t = 0.0f;
static float yaw = 255.0f;
static double heading = std::fmod(std::atan2(INIT_VE, INIT_VN) * RAD_TO_DEG + 360.0, 360.0);
static void reset() {
lat = START_LAT;
lon = START_LON;
alt = START_ALT;
vn = INIT_VN;
ve = INIT_VE;
yaw_t = 0.0f;
heading = std::fmod(std::atan2(ve, vn) * RAD_TO_DEG + 360.0, 360.0);
yaw = static_cast<float>(heading);
}
static void update(double dt) {
lat += (vn * dt) / EARTH_RADIUS_M * RAD_TO_DEG;
lon += (ve * dt) / (EARTH_RADIUS_M * std::cos(lat * DEG_TO_RAD)) * RAD_TO_DEG;
alt -= DESCENT_RATE * dt;
if (alt < 0.0) alt = 0.0;
heading = std::fmod(std::atan2(ve, vn) * RAD_TO_DEG + 360.0, 360.0);
yaw_t += static_cast<float>(dt);
yaw = std::fmod(static_cast<float>(heading) + YAW_AMP * std::sin(YAW_FREQ * yaw_t) + 360.0f, 360.0f);
}
} // namespace SimNav
#ifdef RA_STACK_HWM_ENABLED
struct StackHWM {
UBaseType_t imu = 0;
UBaseType_t altimeter = 0;
UBaseType_t mag = 0;
UBaseType_t gnss = 0;
UBaseType_t ina = 0;
UBaseType_t tof = 0;
UBaseType_t fsm = 0;
UBaseType_t construct = 0;
UBaseType_t transmit = 0;
UBaseType_t receive = 0;
UBaseType_t retain = 0;
UBaseType_t ins = 0;
UBaseType_t neo = 0;
UBaseType_t control = 0;
UBaseType_t sdlog = 0;
UBaseType_t debug = 0;
UBaseType_t eeprom = 0;
} stack_hwm;
#endif
/* END USER PRIVATE VARIABLES */
/* BEGIN USER SETUP */
void UserSetupGPIOBuzzer() {
if constexpr (RA_LED_ENABLED) {
pinMode(USER_GPIO_BUZZER, OUTPUT);
digitalToggle(USER_GPIO_BUZZER);
#if KST
delay(1000);
#else
delay(100);
#endif
digitalToggle(USER_GPIO_BUZZER);
}
led.begin();
led.setBrightness(10);
led.clear();
led.setPixelColor(0, led.Color(0, 0, 255));
led.setPixelColor(1, led.Color(0, 0, 255));
led.show();
led.clear();
led.show();
// Sensors reset GPIO
pinMode(BNO08X_RESET, OUTPUT); // idle HIGH — bno.begin() owns the reset sequence
pinMode(M10S_RESET, OUTPUT);
digitalWrite(M10S_RESET, 1);
delay(20);
digitalWrite(M10S_RESET, 0);
delay(100);
digitalWrite(M10S_RESET, 1);
}
void UserSetupGPIOCamera() {
// Camera trigger pins — idle LOW, driven HIGH during ascent.
// Pre-set ODR before configuring OUTPUT so the pin never glitches HIGH.
digitalWrite(USER_GPIO_CAM1, LOW);
digitalWrite(USER_GPIO_CAM2, LOW);
pinMode(USER_GPIO_CAM1, OUTPUT);
pinMode(USER_GPIO_CAM2, OUTPUT);
digitalWrite(USER_GPIO_CAM1, LOW);
digitalWrite(USER_GPIO_CAM2, LOW);
}
void UserSetupLowPower() {
LowPower.begin();
LowPower.enableWakeupFrom(&XbeeSerial, []() {});
}
void UserSetupActuator() {
controller.init_pid();
// Paraglider Servo
ServoSerial.begin(1'000'000);
// NVIC_SetPriority(UART7_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY);
ServoSerial.setTimeout(5); // at 1 Mbaud a 4-byte response arrives in ~40 µs; 5 ms is generous without burning CPU
controller.driver.hlscl.pSerial = &ServoSerial;
// Initialize servo driver
controller.driver.hlscl.syncReadBegin(sizeof(ServoDriver::IDS), sizeof(controller.driver.rxPacket), 5);
for (size_t i = 0; i < sizeof(ServoDriver::IDS); ++i) {
controller.driver.hlscl.WheelMode(ServoDriver::IDS[i]);
controller.driver.hlscl.EnableTorque(ServoDriver::IDS[i], 1);
}
// Test
for (size_t i = 0; i < 3; ++i) {
controller.driver.write_speed(ServoDriver::IDS[i], 500);
delay(50);
controller.driver.write_speed(ServoDriver::IDS[i], -500);
delay(50);
controller.driver.write_speed(ServoDriver::IDS[i], 0);
}
//DEPLOYMENT SERVO
write_servo_a(pos_a + 10);
write_servo_a(pos_a);
write_servo_b(pos_b + 10);
write_servo_b(pos_b);
}
void UserSetupCDC() {
if constexpr (RA_USB_DEBUG_ENABLED) {
Serial.begin(460800);
delay(2000);
}
}
void UserSetupSPI() {
SPI.setMISO(USER_GPIO_SPI1_MISO);
SPI.setMOSI(USER_GPIO_SPI1_MOSI);
SPI.setSCLK(USER_GPIO_SPI1_SCK);
SPI.setSSEL(NC);
SPI.begin();
}
void UserSetupUSART() {
XbeeSerial.begin(115200);
xbee.begin(XbeeSerial);
}
void UserSetupI2C() {
i2c4.setClock(100000);
i2c4.begin();
i2c4.setTimeout(50);
}
// Bit-bang 9 SCL pulses to release a slave stuck mid-byte, then reinit I2C4.
// Called when elapsed-time detection in CB_ReadI2C indicates a hung transfer.
static void RecoverI2C4() {
pinMode(USER_GPIO_I2C4_SDA, OUTPUT_OPEN_DRAIN);
pinMode(USER_GPIO_I2C4_SCL, OUTPUT_OPEN_DRAIN);
digitalWrite(USER_GPIO_I2C4_SDA, HIGH);
for (int i = 0; i < 9; ++i) {
digitalWrite(USER_GPIO_I2C4_SCL, LOW);
delayMicroseconds(5);
digitalWrite(USER_GPIO_I2C4_SCL, HIGH);
delayMicroseconds(5);
}
// Issue a STOP condition
digitalWrite(USER_GPIO_I2C4_SDA, LOW);
delayMicroseconds(5);
digitalWrite(USER_GPIO_I2C4_SCL, HIGH);
delayMicroseconds(5);
digitalWrite(USER_GPIO_I2C4_SDA, HIGH);
delayMicroseconds(5);
i2c4.end();
UserSetupI2C();
}
void UserSetupSensor(bool skip_bno = false) {
// ── INA236 Battery Monitor (I2C 0x40) ─────────────────────
Serial.println("\n[SENSOR] INA236 Battery Monitor (I2C 0x40)");
pvalid.ina = ina.begin();
Serial.print(" Init: ");
Serial.println(pvalid.ina ? "OK" : "FAIL");
if (pvalid.ina) {
ina.setADCRange(0);
ina.setMaxCurrentShunt(8, 0.008);
ina.setAverage(INA236_64_SAMPLES);
}
// ── BNO08x AHRS (I2C) ─────────────────────────────────────
if (!skip_bno) {
Serial.println("\n[SENSOR] BNO08x AHRS (I2C)");
digitalWrite(BNO08X_RESET, 1);
pvalid.bno = bno.begin(BNO08X_ADDR, i2c4, USER_GPIO_BNO_INT1, BNO08X_RESET);
Serial.print(" Init: ");
Serial.println(pvalid.bno ? "OK" : "FAIL");
if (pvalid.bno) {
bno.enableRotationVector();
}
} else {
digitalWrite(BNO08X_RESET, 1);
pvalid.bno = true;
Serial.println("\n[SENSOR] BNO08x: skipped (wake from sleep)");
}
// ── u-blox M10S GPS (I2C 0x42) ────────────────────────────
Serial.println("\n[SENSOR] u-blox M10S GPS (I2C 0x42)");
pvalid.m10s = m10s.begin(i2c4, 0x42);
Serial.print(" Init: ");
Serial.println(pvalid.m10s ? "OK" : "FAIL");
if (pvalid.m10s) {
m10s.setI2COutput(COM_TYPE_UBX, VAL_LAYER_RAM_BBR, UBLOX_CUSTOM_MAX_WAIT);
m10s.setNavigationFrequency(10, VAL_LAYER_RAM_BBR, UBLOX_CUSTOM_MAX_WAIT);
m10s.setAutoPVT(true, VAL_LAYER_RAM_BBR, UBLOX_CUSTOM_MAX_WAIT);
m10s.setDynamicModel(DYN_MODEL_AIRBORNE4g, VAL_LAYER_RAM_BBR, UBLOX_CUSTOM_MAX_WAIT);
// Poll up to 2 s for a confirmed PVT from the battery-backed RTC.
// getConfirmedDate/Time is stricter than getTimeValid: the module must have
// cross-checked the RTC against an incoming signal at least once.
Serial.print(" RTC time: ");
const uint32_t t_rtc = millis();
bool rtc_valid = false;
while (millis() - t_rtc < 2000) {
if (m10s.checkUblox() && m10s.getConfirmedDate() && m10s.getConfirmedTime()) {
data.hh = m10s.getHour();
data.mm = m10s.getMinute();
data.ss = m10s.getSecond();
snprintf(data.utc, sizeof(data.utc), "%02d:%02d:%02d",
data.hh, data.mm, data.ss);
Serial.printf("%04d-%02d-%02d %02d:%02d:%02d\n",
m10s.getYear(), m10s.getMonth(), m10s.getDay(),
data.hh, data.mm, data.ss);
rtc_valid = true;
break;
}
delay(50);
}
if (!rtc_valid) Serial.println("N/A");
}
// ── VL53L1X ToF Distance (I2C 0x29) ──────────────────────
// Serial.println("\n[SENSOR] VL53L1X ToF Distance (I2C 0x29)");
// tof.setI2CAddress(0x29);
// pvalid.tof = (tof.begin() == 0);
// if (pvalid.tof) {
// tof.setDistanceModeLong();
// tof.setROI(4, 4, 50);
// tof.startTemperatureUpdate();
// tof.setSigmaThreshold(30);
// // tof.setDistanceThreshold(300, 65535, 1); // WINDOW_ABOVE: data-ready only when distance > 500 mm (50 cm)
// }
// Serial.print(" Init: ");
// Serial.println(pvalid.tof ? "OK" : "FAIL");
}
void UserSetupSD() {
// Force-reset SDMMC1 to flush stale DMA/FIFO state from the previous session.
// Without this, HAL_SD_ReadBlocks blocks forever in the RXFIFOHF polling loop
// on warm resets (watchdog, debugger, NVIC reset) where the peripheral is not
// power-cycled.
__HAL_RCC_SDMMC1_FORCE_RESET();
delay(20);
__HAL_RCC_SDMMC1_RELEASE_RESET();
delay(250); // SD spec: 250 ms power-on stabilisation
SD.setDx(USER_GPIO_SDIO_DAT0, USER_GPIO_SDIO_DAT1, USER_GPIO_SDIO_DAT2, USER_GPIO_SDIO_DAT3);
SD.setCMD(USER_GPIO_SDIO_CMD);
SD.setCK(USER_GPIO_SDIO_CK);
pvalid.sd = SD.begin();
// SDMMC1 IRQ defaults to priority 0 (above FreeRTOS configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY).
// Any FreeRTOS API called from within the SDMMC ISR at priority 0 corrupts
// scheduler internals. Lower it here so the ISR sits below the syscall ceiling.
HAL_NVIC_SetPriority(SDMMC1_IRQn, 6, 0);
HAL_NVIC_EnableIRQ(SDMMC1_IRQn);
if (pvalid.sd) {
fs_sd.find_file_name(RA_FILE_NAME, RA_FILE_EXT);
fs_sd.open_one<FsMode::WRITE>();
fs_sd.file() << "DDL,PACKET_COUNT,UTC,TIMESTAMP_EPOCH,MILLIS,STATE,"
"TEAM_ID,MISSION_TIME,PACKET_COUNT,MODE,"
"STATE,ALTITUDE,"
"TEMPERATURE,PRESSURE,VOLTAGE,CURRENT,"
"GYRO_R,GYRO_P,GYRO_Y,"
"ACCEL_R,ACCEL_P,ACCEL_Y,"
"GPS_TIME,GPS_ALTITUDE,GPS_LATITUDE,GPS_LONGITUDE,GPS_SATS,"
"VELOCITY_E,VELOCITY_N,"
"CMD_ECHO,"
"HEADING,"
"ROLL,PITCH,YAW,"
"TOF,DEPLOY,"
"ALT_REF,APOGEE_RAW,"
"POS_A,POS_B,CPU_TEMP,"
"SERVO_1_ANGLE,SERVO_2_ANGLE,SERVO_3_ANGLE,"
"SERVO_1_TARGET,SERVO_2_TARGET,SERVO_3_TARGET\r\n";
fs_sd.file().flush();
// Three short beeps: SD init OK
for (int i = 0; i < 3; ++i) {
digitalWrite(USER_GPIO_BUZZER, HIGH);
delay(100);
digitalWrite(USER_GPIO_BUZZER, LOW);
delay(100);
}
}
}
/* END USER SETUP */
/* BEGIN USER THREADS */
void CB_ReadIMU(void *) {
hal::rtos::interval_loop(RA_INTERVAL_IMU_READING, [&]() -> void {
#ifdef RA_STACK_HWM_ENABLED
stack_hwm.imu = uxTaskGetStackHighWaterMark(NULL);
#endif
mtx_spi.exec(ReadIMU);
const double &ax = data.imu[0].acc_x;
const double &ay = data.imu[0].acc_y;
const double &az = data.imu[0].acc_z;
// Total acceleration
acc = std::sqrt(std::abs(ax * ax) + std::abs(ay * ay) + std::abs(az * az));
// Compensate for gravity
acc = acc - G;
// Update KF with measurement
mtx_kf.exec([&]() { filter_acc.kf.update({acc}); });
});
}
void CB_ReadAltimeter(void *) {
xcore::NbDelay ms5611_delay(100ul, millis);
hal::rtos::interval_loop(RA_INTERVAL_ALTIMETER_READING, [&]() -> void {
#ifdef RA_STACK_HWM_ENABLED
stack_hwm.altimeter = uxTaskGetStackHighWaterMark(NULL);
#endif
if (altimeter_source == 0 || altimeter_source == 2)
mtx_spi.exec([]() { ReadAltimeter(0); }); // BMP581 — SPI
if (altimeter_source == 1 || altimeter_source == 2)
ms5611_delay([&]() { mtx_i2c.exec([]() { ReadAltimeter(1); }); }); // MS5611 — I2C, 100 ms
const bool ok0 = sensors_health.altimeter[0] == SensorStatus::SENSOR_OK;
const bool ok1 = sensors_health.altimeter[1] == SensorStatus::SENSOR_OK;
if (altimeter_source == 1 && ok1) {
data.altimeter_active = data.altimeter[1];
} else if (altimeter_source == 2) {
if (ok0 && ok1) {
data.altimeter_active.altitude_m = (data.altimeter[0].altitude_m + data.altimeter[1].altitude_m) * 0.5;
data.altimeter_active.pressure_hpa = (data.altimeter[0].pressure_hpa + data.altimeter[1].pressure_hpa) * 0.5;
data.altimeter_active.temperature = (data.altimeter[0].temperature + data.altimeter[1].temperature) * 0.5;
} else {
data.altimeter_active = ok1 ? data.altimeter[1] : data.altimeter[0];
}
} else {
data.altimeter_active = ok0 ? data.altimeter[0] : data.altimeter[1];
}
// Update KF with measurement (real or simulated — altitude_m is already set correctly)
mtx_kf.exec([&]() {
filter_alt.kf.update({data.altimeter_active.altitude_m});
});
if (!simActivated && !simEnabled)
alt_agl = data.altimeter_active.altitude_m - alt_ref;
if (alt_agl > apogee_raw)
apogee_raw = alt_agl;
});
}
// Each I2C sensor runs in its own thread at its own rate.
// All threads share mtx_i2c so they never access i2c4 concurrently.
// Per-read timing inside the mutex detects a hung bus and triggers recovery.
void CB_ReadMAG(void *) {
static uint8_t hung_count = 0;
hal::rtos::interval_loop(RA_INTERVAL_MAG_READING, [&]() -> void {
#ifdef RA_STACK_HWM_ENABLED
stack_hwm.mag = uxTaskGetStackHighWaterMark(NULL);
#endif
mtx_i2c.exec([&]() {
const uint32_t t0 = millis();
ReadMAG();
if (millis() - t0 > 40) {
if (++hung_count >= 2) {
hung_count = 0;
RecoverI2C4();
}
} else {
hung_count = 0;
}
});
mtx_nav.exec([&]() { nav_state.yaw = data.yaw; });
});
}
void CB_ReadGNSS(void *) {
static uint8_t hung_count = 0;
hal::rtos::interval_loop(RA_INTERVAL_GNSS_READING, [&]() -> void {
#ifdef RA_STACK_HWM_ENABLED
stack_hwm.gnss = uxTaskGetStackHighWaterMark(NULL);
#endif
mtx_i2c.exec([&]() {
const uint32_t t0 = millis();
ReadGNSS();
if (millis() - t0 > 40) {
if (++hung_count >= 2) {
hung_count = 0;
RecoverI2C4();
}
} else {
hung_count = 0;
}
});
if (data.gps_fresh && gps_fixed) {
mtx_kf.exec([&]() {
// Update east F with current latitude so the coupling dt/(R_lat·cos(lat)) stays accurate
auto F_e = vdt.generate_F();
const double R_lon = GPS_R_LAT * std::cos(data.latitude * (PI / 180.0));
F_e[0][1] /= R_lon;
F_e[0][2] /= R_lon;
filter_nav_e.F = F_e;
// Feed position + velocity measurements into both GPS KFs
filter_nav_n.kf.update({data.latitude, data.velocity_n});
filter_nav_e.kf.update({data.longitude, data.velocity_e});
});
}
// Snapshot filtered GPS state. KF always runs; guidance uses KF or raw depending on RA_USE_KF_GPS flag.
double kf_lat, kf_lon, kf_vn, kf_ve;
mtx_kf.exec([&]() {
kf_lat = filter_nav_n.kf.state_vector()[0];
kf_lon = filter_nav_e.kf.state_vector()[0];
kf_vn = filter_nav_n.kf.state_vector()[1];
kf_ve = filter_nav_e.kf.state_vector()[1];
});
if (gps_fixed) {
if (RA_USE_KF_GPS) {
data.latitude = kf_lat;
data.longitude = kf_lon;
data.velocity_n = kf_vn;
data.velocity_e = kf_ve;
current_location = {kf_lat, kf_lon};
} else {
current_location = {data.latitude, data.longitude};
}
}
mtx_nav.exec([&]() {
if (RA_USE_KF_GPS) {
nav_state.location = {kf_lat, kf_lon};
nav_state.vn = kf_vn;
nav_state.ve = kf_ve;
} else {
nav_state.location = {data.latitude, data.longitude};
nav_state.vn = data.velocity_n;
nav_state.ve = data.velocity_e;
}
nav_state.heading = data.heading_gps;
nav_state.fixed = gps_fixed;
});
});
}
void CB_ReadINA(void *) {
static uint8_t hung_count = 0;
hal::rtos::interval_loop(RA_INTERVAL_INA_READING, [&]() -> void {
#ifdef RA_STACK_HWM_ENABLED
stack_hwm.ina = uxTaskGetStackHighWaterMark(NULL);
#endif
mtx_i2c.exec([&]() {
const uint32_t t0 = millis();
ReadINA();
if (millis() - t0 > 40) {
if (++hung_count >= 2) {
hung_count = 0;
RecoverI2C4();
}
} else {
hung_count = 0;
}
});
});
}
// void CB_ReadTOF(void *) {
// // ReadTOF() splits its two I2C transactions across a 50 ms gap so the bus
// // is free while the sensor integrates. Do NOT wrap it in mtx_i2c.exec()
// // here — that would deadlock on the non-recursive osMutex.
// static uint8_t hung_count = 0;
// static uint8_t stale_count = 0;
// hal::rtos::interval_loop(RA_INTERVAL_TOF_READING, [&]() -> void {
// #ifdef RA_STACK_HWM_ENABLED
// stack_hwm.tof = uxTaskGetStackHighWaterMark(NULL);
// #endif
// if (!pvalid.tof) return;
// data.tof_fresh = false; // cleared here; set true only on a successful read
// const uint32_t t0 = millis();
// ReadTOF();
// // Hung-bus detection: normal cycle is ~55 ms; a full hang (both I2C phases
// // aborting at the 50 ms HAL timeout) takes ~150 ms. 120 ms sits between them.
// if (millis() - t0 > 120) {
// if (++hung_count >= 2) {
// hung_count = 0;
// stale_count = 0;
// mtx_i2c.exec([&]() { RecoverI2C4(); });
// }
// } else {
// hung_count = 0;
// }
// // Stale-data detection: sensor stopped delivering results
// if (data.tof_fresh) {
// stale_count = 0;
// } else if (++stale_count >= 10) {
// // 10 consecutive cycles (~1 s) with no fresh data — reinitialise sensor
// stale_count = 0;
// mtx_i2c.exec([&]() {
// // tof.stopRanging();
// pvalid.tof = (tof.begin() == 0);
// });
// }
// });
// }
void CB_EvalFSM(void *) {
uint32_t true_interval;
hal::rtos::interval_loop(RA_INTERVAL_FSM_EVAL, true_interval, [&]() -> void {
const uint32_t delta_interval = true_interval < RA_INTERVAL_FSM_EVAL
? RA_INTERVAL_FSM_EVAL - true_interval
: true_interval - RA_INTERVAL_FSM_EVAL;
if (true_interval != 0 && // Excluding the first run
delta_interval > RA_JITTER_TOLERANCE_FSM_EVAL) { // If tick jitter is too much
// Update dt for KF
vdt.update_dt(static_cast<double>(true_interval) * 0.001);
// Regenerate F with the new dt
filter_acc.F = vdt.generate_F();
filter_alt.F = vdt.generate_F();
{
auto F = vdt.generate_F();
F[0][1] /= GPS_R_LAT;
F[0][2] /= GPS_R_LAT;
filter_nav_n.F = F;
// filter_nav_e.F is updated in CB_ReadGNSS with the current cos(lat) factor
}
}
#ifdef RA_STACK_HWM_ENABLED
stack_hwm.fsm = uxTaskGetStackHighWaterMark(NULL);
#endif
// Predict states to "now" — locked so sensor update() tasks cannot race predict()
mtx_kf.exec([&]() {
filter_acc.kf.predict();
filter_alt.kf.predict();
filter_nav_n.kf.predict();
filter_nav_e.kf.predict();
});
// FSM with predicted states
EvalFSM();
});
}
void CB_AutoZeroAlt(void *) {
hal::rtos::interval_loop(RA_INTERVAL_AUTOZERO, [&]() -> void {
AutoZeroAlt();
});
}
void CB_ConstructData(void *) {
uint8_t cpu_div = 0;
hal::rtos::interval_loop(RA_INTERVAL_CONSTRUCT, [&]() -> void {
#ifdef RA_STACK_HWM_ENABLED
stack_hwm.construct = uxTaskGetStackHighWaterMark(NULL);
#endif
if (++cpu_div >= 10) {
cpu_div = 0;
data.cpu_temp = ReadCPUTemp();
}
ConstructString();
});
}
void CB_SDLogger(void *) {
static String snap;
static uint8_t flush_counter = 0;
snap.reserve(4096);
// hal::rtos::interval_loop(100ul, [&]() -> void {
hal::rtos::interval_loop(500ul, LoggerInterval, [&]() -> void {
#ifdef RA_STACK_HWM_ENABLED
stack_hwm.sdlog = uxTaskGetStackHighWaterMark(NULL);
#endif
if (!pvalid.sd) return;
mtx_buf.exec([&]() -> void {
snap = sd_buf;
});
mtx_sdio.exec([&]() -> void {
fs_sd.file() << snap.c_str();
// fs_sd.file() << "ebrfujisezfbjkrlkgvbrhui vbgruibui;esgrfbuigesrfd\n";
// Flush only every 10 writes — flush() updates FAT metadata (3+ sectors)
// on every call; doing it at full rate can stall indefinitely on SD GC cycles.
if (++flush_counter >= 10) {
fs_sd.file().flush();
flush_counter = 0;
mtx_cdc.exec([&]() -> void {
// Serial.println("Flushed!");
});
}
mtx_cdc.exec([&]() -> void {
// Serial.println("Logged");
});
});
});
}
void CB_Transmit(void *) {
String snap;
uint8_t xbee_tx_buf[1025];
snap.reserve(1024);
auto send_to = [&](uint64_t addr) {
if (!telemetry_enabled) return;
mtx_buf.exec([&]() { snap = tx_buf; });
mtx_uart.exec([&]() {
XBeeAddress64 dest(addr);
size_t len = min(snap.length(), sizeof(xbee_tx_buf) - 1);
memcpy(xbee_tx_buf, snap.c_str(), len);
xbee_tx_buf[len] = '\n';
Tx64Request tx = Tx64Request(dest, ACK_OPTION, xbee_tx_buf, (uint8_t) (len + 1), DEFAULT_FRAME_ID);
xbee.send(tx);
});
};
hal::rtos::interval_loop(1000ul, [&]() -> void {
#ifdef RA_STACK_HWM_ENABLED
stack_hwm.transmit = uxTaskGetStackHighWaterMark(NULL);
#endif
for (const auto &d: dst) {
send_to(d);
hal::rtos::delay_ms(100);
}
if (telemetry_enabled)
mtx_buf.exec([&]() { ++packet_count; });
});
}
void CB_Control(void *) {
hal::rtos::interval_loop(RA_INTERVAL_Controlling, [&]() -> void {
#ifdef RA_STACK_HWM_ENABLED
stack_hwm.control = uxTaskGetStackHighWaterMark(NULL);
#endif
NavState snap;
if (simActivated) {
// Advance kinematic sim — dt matches the task interval
SimNav::update(RA_INTERVAL_Controlling * 0.001);
snap.location = {SimNav::lat, SimNav::lon};
snap.vn = SimNav::vn;
snap.ve = SimNav::ve;
snap.yaw = SimNav::yaw;
snap.heading = SimNav::heading;
snap.fixed = SimNav::alt > 0.0;
// alt_agl is owned by CB_ReadAltimeter (from simPressure) — do not overwrite here.
} else {
mtx_nav.exec([&]() { snap = nav_state; });
}
// simActivated also sims CB_Control: real GPS/IMU nav is replaced by SimNav synthetic state.
// In real flight only run the spool servos during paraglider descent,
// unless cb_ctrl_enabled is set (uplink test mode with real nav data).
if (!simActivated && !cb_ctrl_enabled && fsm.state() != UserState::PAYLOAD_RELEASE) return;
// Uplink-settable protection: block all servo output when engaged.
if (control_protected) return;
// Smooth yaw through sin/cos EMA to handle 0/360 wrap. Raw body yaw had
// 103 deg std in flight, injecting noise into theta_offset at 20 Hz and
// causing constant sector crossings. alpha=0.15 -> ~300 ms time constant.
static double yaw_sin = 0.0, yaw_cos = 1.0;
constexpr double YAW_EMA_ALPHA = 0.15;
double yr = (snap.yaw + SPOOL_PHYSICAL_OFFSET) * DEG_TO_RAD;
yaw_sin = Guidance::ema_filter(std::sin(yr), yaw_sin, YAW_EMA_ALPHA);
yaw_cos = Guidance::ema_filter(std::cos(yr), yaw_cos, YAW_EMA_ALPHA);
double filtered_yaw = std::atan2(yaw_sin, yaw_cos) * RAD_TO_DEG;
if (filtered_yaw < 0.0) filtered_yaw += 360.0;
double ctrl_alt;
mtx_kf.exec([&]() { ctrl_alt = alt_agl; });
servo_target_angles = controller.guidance.update(snap.location, target_location, ctrl_alt, snap.vn, snap.ve, filtered_yaw, snap.heading);
controller.servo_pid_update(servo_target_angles);
});
}
void CB_ReceiveCommand(void *) {
hal::rtos::interval_loop(10ul, [&]() -> void {
#ifdef RA_STACK_HWM_ENABLED
stack_hwm.receive = uxTaskGetStackHighWaterMark(NULL);
#endif
bool cmd_ready = false;
// 1. Drain serial into the AP=2 state machine; process complete frames
mtx_uart.exec([&]() -> void {
while (XbeeSerial.available()) {
if (xbFeedByte((uint8_t) XbeeSerial.read())) {
if (xb_buf[0] == 0x90 && xb_len >= 12) {
// RX Indicator: 1 type + 8 src addr + 2 reserved + 1 options = 12 header bytes
XBeeAddress64 src_addr(
((uint32_t) xb_buf[1] << 24) | ((uint32_t) xb_buf[2] << 16) | ((uint32_t) xb_buf[3] << 8) | xb_buf[4],
((uint32_t) xb_buf[5] << 24) | ((uint32_t) xb_buf[6] << 16) | ((uint32_t) xb_buf[7] << 8) | xb_buf[8]);