Frequency from input capture
Compute a signal's frequency from two capture timestamps on a 16-bit timer. A medium embedded C problem (Timers and PWM), run and graded in the browser.
medium · Timers and PWM · input-capture · rollover
A timer in input-capture mode latches its 16-bit counter on every rising edge of a signal. The counter runs freely at tick_hz and wraps from 0xFFFF to 0.
Given two consecutive captures, return the signal's frequency in hertz, rounded to the nearest integer. The edges are less than one full counter wrap apart. If the two captures are equal, return 0: there is no measurable signal.
Starter code
uint32_t capture_freq(uint16_t first, uint16_t second, uint32_t tick_hz) {
uint32_t period = second - first;
return tick_hz / period;
}Example tests
Two captures in order
printf("%u\n", capture_freq(1000, 3000, 1000000));Expected output:
500The counter wrapped between the edges
printf("%u\n", capture_freq(65000, 1000, 1000000));Expected output:
651Learn 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.
- 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.
- Fan speed from tach pulses · Compute a fan's RPM from captured tach pulse times, and report 0 when it stalls.
- 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.