Simvik

Fan speed from tach pulses

Compute a fan's RPM from captured tach pulse times, and report 0 when it stalls. A medium embedded C problem (Timers and PWM), run and graded in the browser.

medium · Timers and PWM · input-capture · timing · rollover

A PC fan's tachometer output pulses twice per revolution. An input-capture timer records the time of each pulse in microseconds (a free-running 32-bit counter that rolls over).

fan_rpm(pulse_us, n, now_us) returns the speed in revolutions per minute from the last two pulses: one revolution takes two pulse periods, so rpm = 60,000,000 / (2 × period), rounded to the nearest whole number.

Return 0 if there are fewer than two pulses, or if the last pulse is more than 500,000 µs before now_us: the fan has stalled, and the last period no longer describes it. Times may roll over between pulses.

Starter code

uint16_t fan_rpm(const uint32_t *pulse_us, int n, uint32_t now_us) {
  return (uint16_t)(60000000u / (pulse_us[n - 1] - pulse_us[n - 2]));
}

Example tests

A steady 3000 RPM

const uint32_t t[] = { 1000, 11000 };
printf("%u\n", fan_rpm(t, 2, 12000));

Expected output:

3000

A stalled fan

const uint32_t t[] = { 1000, 11000 };
printf("%u\n", fan_rpm(t, 2, 700000));

Expected output:

0

Learn it first

  • Timers and PWM · Prescalers, auto-reload, input capture, output compare and dead time.

More Timers and PWM problems