Notifications
Clear all

Writing a timing function

18 Posts
7 Users
11 Likes
794 Views
barrie
(@barrie)
Member
Joined: 2 years ago
Posts: 86
Topic starter  

@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?


   
ReplyQuote
barrie
(@barrie)
Member
Joined: 2 years ago
Posts: 86
Topic starter  

@davee You were absolutely right. You gave me the correct structure and I found it easy to modify to suite my requirements. Thank you again.


   
DaveE reacted
ReplyQuote
frogandtoad
(@frogandtoad)
Member
Joined: 5 years ago
Posts: 1458
 

@barrie

Posted by: @barrie

@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


   
ReplyQuote
Page 2 / 2