-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
36 lines (29 loc) · 1.28 KB
/
Copy pathmain.cpp
File metadata and controls
36 lines (29 loc) · 1.28 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
#include <Arduino.h>
#include "flight_computer.h"
// The PD loops assume a fixed cadence - their derivative term is only meaningful if dt is
// constant. 20 ms is the 50 Hz they are written for; the period lives here and nowhere else.
static const uint32_t CONTROL_PERIOD_MS = 20;
static uint32_t nextCycleMs = 0;
void setup() {
Serial.begin(9600);
initFlightComputer();
nextCycleMs = millis();
}
void loop() {
const uint32_t now = millis();
// millis() wraps at 2^32 ms, about every 49 days. Subtracting first and reading the
// result as signed keeps the deadline comparison correct across that wrap, which is why
// both sides are pinned to 32 bits rather than left as int/long.
if ((int32_t)(now - nextCycleMs) < 0) {
return;
}
nextCycleMs += CONTROL_PERIOD_MS;
// A cycle that overran by a full period or more would otherwise be followed by a burst
// of back-to-back catch-up cycles. Give up the lost time instead. The comparison is
// >= rather than > because an overrun of exactly one period leaves the new deadline
// sitting on the current millisecond, which is a catch-up cycle with no wait in it.
if ((int32_t)(now - nextCycleMs) >= 0) {
nextCycleMs = now + CONTROL_PERIOD_MS;
}
updateFlightComputer();
}