Assume that we want to have the for loop generate a one millisecond delay. The time to execute a software delay loop is proportional to the number of times the loop must be executed, as expressed in the following:
Given that the single loop execution time is constant, then the following relationship is also true:
where
$T_{\mathrm{DELAY\_1}}$ = Actual delay time measured by monitoring the test point for LEDA.
$T_{\mathrm{DELAY\_2}}$ = The desired loop delay.
COUNTS_PER_MS_1 = Initial or previously computed number of for-loop iterations to generate a one millisecond delay.
COUNTS_PER_MS_2 = Updated computed value of COUNTS_PER_MS.
Suppose that using a particular value for COUNTS_PER_MS_1 in our software delay function results in a delay, $T_{\mathrm{DELAY\_1}}$, that is not equal to our desired 1ms delay, $T_{\mathrm{DELAY\_2}}$. Rearranging Eq. (2) allows us to solve for an updated COUNTS_PER_MS needed to implement the desired delay, as shown below:
We can start with any initial guess for COUNTS_PER_MS_1, provided that it is in the numerical range of an unsigned integer. After running the program using our initial guess, we then take the measurement to determine the actual delay, $T_{\mathrm{DELAY\_1}}$. Using the ratio of the desired delay to the actual delay and multiplying by the value we used for COUNTS_PER_MS_1 allows us to compute the new value for COUNTS_PER_MS_2.
In theory, the new value computed for COUNTS_PER_MS_2 will result in the desired delay. However, the proportionality of Eq. (2) is only approximate and it may require a few iterations of solving Eq. (3) to achieve an accurate delay. The solution converges whenever the measured delay matches the desired delay. The following procedure can be used to determine the correct value of COUNTS_PER_MS to achieve a one millisecond loop delay.