Calibrate a busy-wait delay
Work out how many loop passes give a delay, without overflowing. An easy embedded C problem (CPU fundamentals for embedded), run and graded in the browser.
easy · CPU fundamentals for embedded · cpu · cycles · timing
A short busy-wait delay (for example the 10 µs a sensor needs after a command) is often a loop that burns a known number of cycles per pass.
Write delay_loops(cpu_hz, delay_us, cycles_per_loop): the number of loop passes needed for at least delay_us microseconds at cpu_hz, when each pass takes cycles_per_loop cycles. Round up, so the delay is never shorter than asked. The intermediate product cpu_hz × delay_us does not fit in 32 bits for long delays: use 64-bit arithmetic.
Starter code
uint32_t delay_loops(uint32_t cpu_hz, uint32_t delay_us, uint32_t cycles_per_loop) {
return cpu_hz / 1000000u * delay_us / cycles_per_loop;
}Example tests
10 us at 16 MHz
show(16000000u, 10, 4);Expected output:
16000000 Hz, 10 us, 4 cycles/pass: 40 passesA clock that is not whole megahertz
show(7372800u, 100, 3);Expected output:
7372800 Hz, 100 us, 3 cycles/pass: 246 passesLearn it first
- CPU fundamentals for embedded · Pipelines, caches, DMA coherency, barriers and buses.