Simvik

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:

500

The counter wrapped between the edges

printf("%u\n", capture_freq(65000, 1000, 1000000));

Expected output:

651

Learn it first

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

More Timers and PWM problems