Simvik

Flash wait states for a clock

Pick how many wait states flash needs at a given clock and supply voltage. An easy embedded C problem (MCU cores and clocking), run and graded in the browser.

easy · MCU cores and clocking · clocks · flash · stm32

Flash memory is slower than a fast CPU, so above a certain clock the CPU must wait extra cycles (wait states) on every flash read. Set too few and the CPU reads garbage; set too many and code runs slower than it could.

An STM32F4's reference manual gives the clock each wait state allows, by supply voltage:

SupplyClock per wait state
2.7 to 3.6 V30 MHz
2.4 to 2.7 V24 MHz
2.1 to 2.4 V22 MHz
1.8 to 2.1 V20 MHz

So at 3.3 V, up to 30 MHz needs 0 wait states, up to 60 MHz needs 1, and so on. Write flash_ws(hclk_hz, supply_mv) returning the minimum number of wait states (-1 below 1.8 V).

Starter code

int flash_ws(uint32_t hclk_hz, int supply_mv) {
  (void)supply_mv;
  return (int)(hclk_hz / 30000000u);
}

Example tests

168 MHz at 3.3 V

show(168000000u, 3300);
show(16000000u, 3300);

Expected output:

168 MHz at 3300 mV: 5
16 MHz at 3300 mV: 0

Exactly on a boundary

show(30000000u, 3300);
show(60000000u, 3300);

Expected output:

30 MHz at 3300 mV: 0
60 MHz at 3300 mV: 1

Learn it first