Reputation: 1
I'm looking to create 250ms delay function with MikroC. In the code below, I don't understand what 165 in the 2nd for section does.
void MSDelay(unsigned int itime); // this is the prototype
void MSDelay(unsigned int itime) {
unsigned int i;
unsigned char j;
for(i=0;i<itime;i++) {
for(j=0;j<165;j++); }
}
}
Upvotes: -1
Views: 1142
Reputation: 68
There is already a function provided in Mikroc which is responsible for producing delay of milliseconds, i.e. delay_ms() , the nested loop in the program is doing nothing but it keeps microcontroller busy for some microseconds or milliseconds, thus preventing the program to move further without completing the loop, while just moving into loop cycles, the microcontroller is just made to execute specific instructions like nop (in assembly), this instructions require some instruction cycles, that needs time to execute (inversely proportional to FSOC ), thus without altering anything in the program the microcontroller produces delay.
Upvotes: 0
Reputation: 31403
MikroC provides the built-in function Delay_ms for producing simple blocking software delays.
Delay_ms(250);
This should work unless you have other specific constraints.
The method you've shown is a bit of a hack. For some specific PIC with a specific clock an empty for
loop with 165 iteration likely takes about 1ms, so the outer loop simply counts milliseconds by running the inner loop itime
times for itime
milliseconds.
You should not use a method like this because it is highly specific to a particular PIC running at a particular clock speed and also depends on the compiler not simply optimizing away the whole loop. The built-in delay function should always just do the right thing no matter which PIC you're building for.
Upvotes: 3