Speeduino
Loading...
Searching...
No Matches
Functions
elapsed_time.h File Reference

Rollover-safe elapsed time calculations for free-running counters. More...

#include <stdint.h>
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

static uint32_t timeElapsed (uint32_t now, uint32_t start)
 Compute the number of counter ticks elapsed from start to now.
 
static bool hasIntervalElapsed (uint32_t now, uint32_t start, uint32_t interval)
 Check whether at least interval counter ticks have elapsed since start.
 

Detailed Description

Rollover-safe elapsed time calculations for free-running counters.

Timestamps taken from free-running counters such as micros(), millis() or runSecsX10 wrap back to zero when the counter overflows (micros() every ~71.6 minutes). Comparing absolute timestamps, E.g. micros() > startTime + interval, breaks when either the addition overflows or the counter wraps between the two samples. Unsigned modular subtraction is exact across a single wrap, so elapsed-time based comparisons remain correct provided the real elapsed time is less than one full counter period (I.e. the check runs at least once per counter period).

Both functions take now as a parameter rather than calling micros() internally so that callers can be unit tested with arbitrary counter values, including values either side of the wrap point.

Function Documentation

◆ hasIntervalElapsed()

static bool hasIntervalElapsed ( uint32_t  now,
uint32_t  start,
uint32_t  interval 
)
inlinestatic

Check whether at least interval counter ticks have elapsed since start.

Rollover-safe replacement for now >= start + interval style comparisons. The boundary is inclusive: an elapsed time exactly equal to interval counts as elapsed.

Parameters
nowThe current counter reading (E.g. micros())
startThe counter reading taken when the interval started
intervalThe minimum number of ticks that must have elapsed
Returns
true if at least interval ticks have elapsed since start
Here is the call graph for this function:
Here is the caller graph for this function:

◆ timeElapsed()

static uint32_t timeElapsed ( uint32_t  now,
uint32_t  start 
)
inlinestatic

Compute the number of counter ticks elapsed from start to now.

Correct across counter rollover thanks to unsigned modular arithmetic, as long as the real elapsed time is less than one full counter period.

Parameters
nowThe current counter reading (E.g. micros())
startThe counter reading taken when the interval started
Returns
The number of ticks elapsed between the two readings
Here is the caller graph for this function: