I want to generate delay in generalized manner i.e void delay(uint8_t delay_ms). The delay passed in ms.
. So I am using LPC1317-64P, 72MhZ clock.
So to generate delay I have used function, SYSTEM_FREQ = 72000KHZ
void delay(uint8_t delay_ms) { uint32_t cnt,temp; cnt = delay_ms*SYSTEM_FREQ for(temp = cnt;temp>0;temp--) //i.e calling NOP the number of times { __NOP(); } }
Problem is in disammembly the for loops break down into MOV,NOP,SUBS,BNE instruction. So total delay is not the same. Its takes 10 times more time. As might be in assembly it has 10 cycles .
If I divide by cnt by 10, then delay is fine. Small inaccuracy is acceptable.
Also I have used Hi Tech C compiler, there when I use __delay_ms(2), it generate exact 2ms delay. How to do that in C.
you have three lines for the nop. so you need to change your math to
cnt = (delay_ms*SYSTEM_FREQ)/3
it is perfect
No. Delays in the ms range using a for loop really is not perfect. It is lousy. Busy-loops can be good for minimal ns or us delays where the requirement isn't an exact delay but a guranteed minimum delay. But that doesn't mean they are trivial to implement, since the compiler can throw them away if incorrectly written - and their speed must be verified.
But if you want a 500ms delay, you normally want 500ms independent of what other things the processor does. So 0% or 50% interrupt load should only give a bit of jitter in the timing - not a factor two difference pusing 500ms -> 1000ms.
And you do not want an implementation where a change of code optimization settings, or a change of compiler version, suddenly makes a huge difference to the delay.
And you do not want an implementation where the delay could actually become almost zero, because all of the loop gets thrown away for having zero side effects. Better compilers specifically knows about their "nop" intrinsics and makes sure they aren't optimized away - but there are seldom any compiler documentation that explicitly says so.
Why do we so seldom see people who have used timers when implementing their delay loops post their troubles on this forum? Might it be because they so seldom have problems? That their delays actually do what was intended, without interferences from lots of unknowns inside the compiler or other things the processor may be busy doing?