I recently had to make an Arduino project using avr library and without delay lib. In that i had to create an implementation of the delay function.
After searching on the internet i found this particular code in many many places. And the only explanation i got was it kills time in a callibrated manner.
void delay_ms(int ms) {
int delay_count = F_CPU / 17500;//Where is this 17500 comming from
volatile int i;
while (ms != 0) {
for (i=0; i != delay_count; i++);
ms--;
}
}
iam not able to understand how the following works,(though it did do the job) i.e., how did we determine delay count to be F_cpu/17500. Where is this number comming from.
Delay functions is better to be done in assembly, because you must know how many instruction cycle your code take to know how to repeat it to achieve the total delay.
I didn't test your code but this value (17500) is designed to reach 1ms delay.
for example if F_CPU = 1000000
so delay_count = 57
, to reach 1ms it count 57 count a simple calculation you could found that every count will take 17us and this value is the time for loop take when compiled to assembly.
But of course different compiler versions will produce different assembly code which means inaccurate delay.
My advice to you is to use standard avr/delay.h library. i cannot see any reason why can't you use it? But if you must create another one so you should learn assembly!!