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:
3000A stalled fan
const uint32_t t[] = { 1000, 11000 };
printf("%u\n", fan_rpm(t, 2, 700000));Expected output:
0Learn it first
- Timers and PWM · Prescalers, auto-reload, input capture, output compare and dead time.
More Timers and PWM problems
- Servo pulse width · Turn an angle into the compare value for a hobby servo's pulse.
- Prescaler and auto-reload · Choose PSC and ARR for a 16-bit timer to hit an update frequency.
- Frequency from input capture · Compute a signal's frequency from two capture timestamps on a 16-bit timer.
- Duty cycle from captures · Measure a PWM signal's duty cycle in tenths of a percent.
- Decode a quadrature encoder · Turn A/B channel transitions into +1, -1 or 0 steps with a lookup table.
- Software PWM · Drive four PWM channels from a timer tick on pins without PWM hardware.
- Fix: long delays end far too early · Delays over about four seconds come out wrong.
- Driver: a millisecond delay on a hardware timer · Program a timer's prescaler and auto-reload, and wait for exactly one period.
- Fix: 100 % brightness still flickers · A duty-cycle conversion uses the auto-reload value instead of the period length.
- Greenhouse: fan speed from temperature · Map a temperature to a PWM duty cycle, without stalling the fan at low speed.
- Robot gripper: servo angle to timer value · Turn a servo angle into the timer's compare value, within the gripper's mechanical limits.