Skip to content

Commit 841ffe7

Browse files
authored
Fix clock_gettime rollover (#159)
* Fix clock_gettime rollover * Fix * Fix
1 parent 4fc35f9 commit 841ffe7

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

src/default_transport.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,25 @@ extern "C"
1212
size_t arduino_transport_write(struct uxrCustomTransport * transport, uint8_t *buf, size_t len, uint8_t *errcode) __attribute__ ((weak));
1313
size_t arduino_transport_read(struct uxrCustomTransport * transport, uint8_t *buf, size_t len, int timeout, uint8_t *errcode) __attribute__ ((weak));
1414

15+
#define micro_rollover_useconds 4294967295
16+
1517
int clock_gettime(clockid_t unused, struct timespec *tp)
1618
{
1719
(void)unused;
20+
static uint32_t rollover = 0;
21+
static uint64_t last_measure = 0;
22+
1823
uint64_t m = micros();
1924
tp->tv_sec = m / 1000000;
2025
tp->tv_nsec = (m % 1000000) * 1000;
26+
27+
// Rollover handling
28+
rollover += (m < last_measure) ? 1 : 0;
29+
uint64_t rollover_extra_us = rollover * micro_rollover_useconds;
30+
tp->tv_sec += rollover_extra_us / 1000000;
31+
tp->tv_nsec += (rollover_extra_us % 1000000) * 1000;
32+
last_measure = m;
33+
2134
return 0;
2235
}
2336

0 commit comments

Comments
 (0)