blob: 3ca9984cf1ca6efe8bf90a01aed7b8d46894d9b4 [file] [log] [blame]
Brian Silverman7be68ba2020-01-08 22:08:40 -08001#include "frc971/wpilib/fpga_time_conversion.h"
2
3#include "aos/util/compiler_memory_barrier.h"
4
Stephan Pleinesf63bde82024-01-13 15:59:33 -08005namespace frc971::wpilib {
Brian Silverman7be68ba2020-01-08 22:08:40 -08006
7std::optional<std::chrono::nanoseconds> CalculateFpgaOffset() {
8 aos_compiler_memory_barrier();
9 const hal::fpga_clock::time_point fpga_time_before = hal::fpga_clock::now();
10 aos_compiler_memory_barrier();
11 const aos::monotonic_clock::time_point monotonic_now =
12 aos::monotonic_clock::now();
13 aos_compiler_memory_barrier();
14 const hal::fpga_clock::time_point fpga_time_after = hal::fpga_clock::now();
15 aos_compiler_memory_barrier();
16
17 const std::chrono::nanoseconds fpga_sample_length =
18 fpga_time_after - fpga_time_before;
19
20 if (fpga_sample_length < fpga_sample_length.zero()) {
21 return std::nullopt;
22 }
23 if (fpga_sample_length > std::chrono::microseconds(20)) {
24 return std::nullopt;
25 }
26
27 const std::chrono::nanoseconds fpga_average =
28 (fpga_time_after.time_since_epoch() +
29 fpga_time_before.time_since_epoch()) /
30 2;
31 return monotonic_now.time_since_epoch() - fpga_average;
32}
33
Stephan Pleinesf63bde82024-01-13 15:59:33 -080034} // namespace frc971::wpilib