Files
Interval/src/interval.cpp

83 lines
2.3 KiB
C++

#include "interval.h"
// Returns the remaining time until expiration, correctly handling overflow
uint32_t Interval::remains() const {
uint32_t currentTime = millis();
return _timeout - (currentTime - _timefrom);
}
// Returns the elapsed time since the interval started
uint32_t Interval::elapsed() const {
return millis() - _timefrom;
}
// Checks if the interval has expired based on the mode
bool Interval::expired() {
uint32_t currentTime = millis();
uint32_t elapsedTime = currentTime - _timefrom;
switch (_mode) {
case ONESHOT:
// In oneshot mode, return true only once upon expiration
if (elapsedTime >= _timeout) {
if (_active) {
_active = false;
return true;
}
}
break;
case PERIODIC:
// In periodic mode, return true and reset the timer on expiration
if (elapsedTime >= _timeout) {
_timefrom += _timeout;
if (currentTime - _timefrom >= _timeout) {
_timefrom = currentTime;
}
return true;
}
break;
case COMPATIBILITY:
default:
// In compatibility mode, always return true if the interval has expired
if (_active) {
if (elapsedTime >= _timeout) {
_active = false;
return true;
}
} else {
return true; // already expired
}
break;
}
return false;
}
// Sets the interval in compatibility mode
void Interval::set(const uint32_t tmout) {
_timefrom = millis();
_timeout = tmout;
_mode = COMPATIBILITY;
_active = true;
}
// Sets the interval in oneshot mode
void Interval::setOneshot(const uint32_t tmout) {
_timefrom = millis();
_timeout = tmout;
_mode = ONESHOT;
_active = true;
}
// Sets the interval in periodic mode
void Interval::setPeriodic(const uint32_t tmout) {
_timefrom = millis();
_timeout = tmout;
_mode = PERIODIC;
}
// Reloads the interval timer (resets the starting time)
void Interval::reload() {
_timefrom = millis();
_active = true;
}