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.
A big mistake you do is to ignore the timd needed by the loop. The total loop time id not 0.5+0.5 us.
You are not even in control of the code generated.
Consider making the smallest loop step 10us instead of 1us. And consider making it in an assembler file.
View all questions in Keil forum