NLed
NLed

Reputation: 1865

Easiest way to create a timer in seconds?

What is the easiest and simplest way to create a decrementing timer in seconds?

Im using an 8bit microcontroller and cannot use float points or intensive processes. I need a very efficient timer.

Upvotes: 2

Views: 577

Answers (2)

9000
9000

Reputation: 40894

It looks like you want an asynchronous timer. On a 8-bit controller I suppose you don't have multithreading. But you probably have direct access to hardware timers; most 8-bit controllers have several. Either allocate one of the timers for your needs, or use an existing one with known period. It is as efficient as you can get.

Every time the timer ticks, you receive an interrupt. This may be every second or more frequently. Update a variable that keeps time, and return from the interrupt handler (or pass control to a chained handler if you hook on a timer used for other needs).

If the time-keeping variable is over the threshold, that's your event; take your action. Be sure not to make this action take too long, and consult your controller reference regarding actions not allowed within interrupt handlers.

Upvotes: 1

Adam Rosenfield
Adam Rosenfield

Reputation: 400304

time(2) is a standard C function for obtaining the current time in seconds since the epoch (midnight on January 1, 1970 UTC). To make a decrementing timer, you could do something like this:

time_t startTime = time(NULL);

time_t timerDuration = 10;  // 10 second timer
time_t endTime = startTime + timerDuration;
while(1)
{
    time_t currTime = time(NULL);
    time_t timeLeft = endTime - currTime;

    if(timeLeft < 0)
    {
        // timer has finished
        break;
    }

    // do stuff - preferably don't spin at 100% CPU
}

If you need more precision than 1-second increments, you can use a platform-specific function such as gettimeofday(3) (POSIX) or GetLocalTime (Windows).

Upvotes: 3

Related Questions