What library for running background timer?

I'm not sure what the proper terminology would be for this, so it's been difficult to find the right library. Essentially I want to start a timer that'll run and not stop my code, like "delay" would do. What library would be appropriate for this?

I'm looking to do something like:
if(conditions == True)
{start.timer}

open launch doors, prepare rocket engines, etc. etc. do cool C++ stuff...

if (timer == X seconds)
{launch nukes, do more stuff}

Have a look at this:

millis() is a function that keeps track of how many milliseconds have passed since startup, and by taking a snapshot of it, and comparing that to the current value you can use as a timer.

unsigned long startTime = millis()

void loop()
{
  if (millis() - startTime > 5000)  // Has 5 seconds passed?
  {
    startTime = millis();        // Restart the timer.

    // Do stuff
  }
}

That is one of the uses of the millisecond timer. See this excellent tutorial: https://www.baldengineer.com/blink-without-delay-explained.html

I plan to have the arduino on for a very long time, so I know millis has limits and eventually rolls over back to zero. Right? So would that still work for me?

1 Like

Yes the code above will still work when millis() rolls over (after about 49 days).

22 posts were split to a new topic: To reset or not to reset? millis rollover is the question

From what I can see, the timer just keeps running. But what if I want to start and stop the timer? How do I do that when millis() is tracking how long the arudino has been running?

To start the timer just update startTime with the current value of millis();

A millis( ) based TIMER works perfectly.

https://www.gammon.com.au/millis

@red913 you should try this

awesome! Thanks @red913 ! That's just what I was looking for.

You're welcome. Try searching a bit better next time.

Cute library. The author is obvsly and properly very proud to give it to the world.

But you should really learn how to do everything that library can do.

Here's the basis for all the "magic" in that library:

	curMills = millis();
	if (curMills - preMills >= delaytime)
	{
		preMills = curMills;

The library only works if the required functions get regular attention in your loop().

Which means you kinda have to know how to do free running non blocking code in the first place.

It works no miracles.

a7

2 Likes

Well it was easier to use the library. I rarely write code, so I’ll stick with the library for now. If this comes up again later on a different project, I’ll do it the way you all suggested.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.