user5832523
user5832523

Reputation: 29

Time of day clock.

Question: Suppose that you have a clock chip operating at 100 kHz, that is, every ten microseconds the clock will tick and subtract one from a counter. When the counter reaches zero, an interrupt occurs. Suppose that the counter is 16 bits, and you can load it with any value from 0 to 65535. How would you implement a time of day clock with a resolution of one second.

My understanding: You can't store 100,000 in a 16 bit counter, but you can store 50,000 so could you would you have to use some sort of flag and only execute interrupt every other time?

But, i'm not sure how to go about implement that. Any form of Pseudocode or a general explanation would be most appreciated.

Upvotes: 1

Views: 279

Answers (1)

John
John

Reputation: 3807

Since you can't get the range you want in hardware, you would need to extend the hardware counter with some sort of software counter (e.g. everytime the hardware counter goes up, increment the software counter). In your case you just need an integer value to keep track of whether or not you have seen a hardware tick. If you wanted to use this for some sort of scheduling policy, you could do something like this:

static int counter; /* initilized to 0 somewhere */

void trap_handler(int trap_num)
{
    switch(trap_num)
    {
        ...
        case TP_TIMER:
            if(counter == 0)
                counter++;
            else if(counter == 1)
            {
                /* Action here (flush cache/yield/...)*/
                fs_cache_flush();   
                counter = 0;
            } else {
                /* Impossible case */
                panic("Counter value bad\n");
            }
            break;
         ...
         default:
             panic("Unknown trap: 0x%x\n", trap_num)
             break;
    }

    ...
}

If you want example code in another language let me know and I can change it. I'm assuming you're using C because you tagged your question with OS. It could also make sense to keep your counter on a per process basis (if your operating system supports processes).

Upvotes: 1

Related Questions