I want to create delay functions in a separate c file. The code should be as perfect as possible without using internal timer. I read somewhere that 'Calling the routine takes about 22us' Though 22uS may be different for my cpu clock, if possible this factor should also be taken into account.
I am using 89S52 with 24Mhz crystal. I tried following code.
void usdelay(unsigned int us){ while (us--){ _nop_(); //0.5uS single-cycle instruction delay _nop_(); //0.5uS single-cycle instruction delay } } void msdelay(unsigned int ms){ unsigned long tm = 1000*ms; while (tm--){ _nop_(); //0.5uS single-cycle instruction delay _nop_(); //0.5uS single-cycle instruction delay } } void secdelay(unsigned int sec){ unsigned long tm = 1000*sec; while (tm--){ msdelay(1); } }
The problem is that the uS & ms delays are proper (may be - I have not measured them), but it takes very long to finish secdelay with 1 sec timing. Please HELP.
Increasing the number of NOP's will make the relative contribution of function entry and exit smaller. If you don't need fine delay granularity and have some code memory to spare, make it 100 NOP's in a row or so.