Skip to content

Instantly share code, notes, and snippets.

@Eibwen
Last active April 9, 2020 15:52
Show Gist options
  • Save Eibwen/d892b0cf815f9b1b1e538cf1f5a67412 to your computer and use it in GitHub Desktop.
Save Eibwen/d892b0cf815f9b1b1e538cf1f5a67412 to your computer and use it in GitHub Desktop.
/*
* Encapsulate the logic of running something on an interval in a simple class which returns a boolean
* Usage:
* // Create a global variable to keep the state
* IntervalWithoutDelay operationName = new IntervalWithoutDelay(1000);
* IntervalWithoutDelay slowerOperation = new IntervalWithoutDelay(5000);
*
* void loop(void) {
* unsigned long currentMillis = millis();
*
* if (operationName.RunNow(currentMillis)) {
*
* // My operation which should run approximately once per second
*
* }
* if (slowerOperation.RunNow(currentMillis)) {
*
* // My operation which should run approximately once per 5 seconds
*
* }
* }
*/
class IntervalWithoutDelay {
unsigned long _updateRate;
unsigned long _previousMillis;
public:
IntervalWithoutDelay (unsigned long updateRate)
{
_updateRate = updateRate;
}
bool RunNow(unsigned long currentMillis)
{
if ((currentMillis - _previousMillis) >= _updateRate)
{
_previousMillis = currentMillis;
return true;
}
return false;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment