#20 - Variable timer
There has been a few discussions about how to vary the interval time of a timer… I have even used one way in an earlier post above with the adjustable servo sweep.
But here is an easier way… use a one-shot Timeout Timer instead…
Create your function that you want to run on a variable interval, but don’t call that function with an outside timer, just call it the first time (if you want) in your setup or upon Blynk connect, or even wait until you chose a time, etc.
Then, using a global variable acquired from some other source (Slider, Step Control, Numeric input, etc.) end your custom timed function with a timeout timer, set to the required variable, that calls the same function it is already in.
If you really want to get fancy, you can setup Timer IDs and run a delete timer at the beginning of the function, thus allowing you to interrupt and cancel whatever previous setting… preventing duplicate function runs from leftover timeout timers.
long variableTime = 1000; // default interval time of 1 second
int varTimer; // Setup Timeout Timer ID
BLYNK_WRITE(V0) { // Widget for interval timing
variableTime = param.asInt();
if (variableTime <= 0) { // prevents a timer from becoming 0 or less
variableTime = 1;
}
timerLoop(); // Call your timed loop
}
void timerLoop() {
timer.deleteTimer(varTimer); // Cancel previous Timeout Timer
//
// Do your stuff here every (variableTime) seconds
//
varTimer = timer.setTimeout(variableTime, timerLoop); // Set new Timeout timer
}