Add an accurate delay loop.

The existing 'delay' function is not calibrated to any specific measure
of time. Add a new function using a loop with a known cycle count, to
produce delays of a given duration at a given CPU clock speed.
This commit is contained in:
Martin Ling
2022-06-13 16:32:55 +01:00
parent fa0662e54c
commit 273e6a1217

View File

@ -299,6 +299,19 @@ void delay(uint32_t duration)
__asm__("nop"); __asm__("nop");
} }
void delay_us_at_mhz(uint32_t us, uint32_t mhz)
{
// The loop below takes 4 cycles per iteration.
uint32_t loop_iterations = (us * mhz) / 4;
asm volatile (
"start%=:\n"
" subs %[ITERATIONS], #1\n" // 1 cycle
" bpl start%=\n" // 3 cycles
:
: [ITERATIONS] "r" (loop_iterations)
);
}
/* GCD algo from wikipedia */ /* GCD algo from wikipedia */
/* http://en.wikipedia.org/wiki/Greatest_common_divisor */ /* http://en.wikipedia.org/wiki/Greatest_common_divisor */
static uint32_t static uint32_t