@zander Oh dear, silly me. I should have said that I posted the code simply as a comparison with @davee 's code and not for analysis so I did not bother with the format. @davee 's code was based on my original where I purposely set lastTime to zero when I was testing. The post was in answer to @frogandtoad 's question with reference @frogandtoad 's comment on @davee 's code. In the meantime the elapsedTime function is working as expected. Thanks to y'all here.
Um... are you sure you didn't mean that @inq code worked first time for you?
Please see my previous post on Dave's code, as I just can't see how it worked for you without any tweeks?
@frogandtoad I believe I was correct, @davee 's code did work as is with no tweeks and no globals. Here it is pasted directly from my script. I only tested it with an LED that turned on after interval set at 10000. I have yet to use it extensively and thanks to your analysis, I should be able to fix the "interval" and "lastTime" issues. Maybe I should set them as global variables with "return false" above "lastTime". Does that make sense?
bool elapsedTime (unsigned long interval){unsigned long currentTime = millis();unsigned lastTime = 0;if (currentTime - lastTime >= interval){return true;interval = 0;}else{lastTime = millis();return false;}}
The code as you've shown here will still not work correctly, as interval cannot be set after the return function, and is not required anyway, and likewise missing the static variable to track the lastTime recorded - Once this kicks off, it will just loop at the full speed the main loop allows.
This is easy to test so you understand what's happening - Just add a print statement in the if true condition, and compare this with the version of code @inq posted to see the difference.
Cheers