Page 1 of 1
Implementing Delay Function
Posted: Thu Dec 18, 2003 12:20 pm
by HDA
could u please explain me about implementing the delay function in C?
tnx
Re:Implementing Delay Function
Posted: Thu Dec 18, 2003 1:43 pm
by Tim
Set up a handler for IRQ0, the timer interrupt. In your timer interrupt handler, increment a global variable (for example, uptime).
Then delay will look like this:
Code: Select all
void delay(unsigned milliseconds)
{
unsigned end;
end = uptime + milliseconds * TICKS_PER_MILLISECOND;
while (uptime < end)
;
}
Note that you can only call this delay function when interrupts are enabled.
For extra points:
-- put a __asm__("hlt") into the while loop
-- implement timers in your scheduler so that other tasks can run while one is inside delay
Re:Implementing Delay Function
Posted: Fri Dec 19, 2003 4:26 am
by Pype.Clicker
The above code is indeed the simplest possible approach. Note that in order to have it working,
uptime must be a
volatile global variable, so that you prevent the compiler from optimizing things into
Code: Select all
mov eax,[uptime]
mov ebx,[end]
.loop:
cmp eax,ebx
jle .loop
Another thing that troubles me is that in most cases, your timer will hardly tick more than once per millisecond (people tend to have 100Hz or 18.2Hz timers ... I do have 1KHz one =)
This means that TICKS_PER_MILLISECOND is likely to be a float and i dunno if end = uptime + (milliseconds * TICKS_PER_MILLISECOND) will not involve math library functions ...
i would rather have gone for
Code: Select all
end = uptime + milliseconds / MILLISECONDS_PER_TICKS;
Re:Implementing Delay Function
Posted: Fri Dec 19, 2003 5:00 am
by Tim
Oops! Good point Pype.
Myself, I have the uptime variable holding a value in milliseconds, and increment it by MILLISECONDS_PER_TICK in my IRQ0 handler. Even when using MILLISECONDS_PER_TICK, the PIT isn't going to give you an integer period, so you can either:
-- use a float MILLISECONDS_PER_TICK (probably not)
-- correct the global uptime value every so often (say, per minute) with a small tweak
-- grab the time from the real-time clock every so often and put it in uptime
Re:Implementing Delay Function
Posted: Fri Feb 06, 2004 1:24 am
by guest
I'm slightly confused here. When we program the PIT for 100hz frequency we use the value 1193180/100. giving 11932(approx). Now the relation between freq and time is t=1/f therefore the time this freq represents is 1/100 or 0.01 sec (or 10 millisecs??). is this calculation right? Then does this mean that every 10 millisec we get an IRQ? then the value of TICKS_PER_MILLISEC is 10 is this right? (I know i'm wrong somewhere here but not sure where)
Re:Implementing Delay Function
Posted: Fri Feb 06, 2004 3:01 am
by Pype.Clicker
no. if you have one IRQ every 10 milliseconds, TICKS_PER_MILLISECOND should be set to 0.1