Simvik

Duty cycle from captures

Measure a PWM signal's duty cycle in tenths of a percent. A medium embedded C problem (Timers and PWM), run and graded in the browser.

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

Two capture channels on the same free-running 16-bit timer record a PWM signal's rising edge (rise1), the falling edge after it (fall) and the next rising edge (rise2). The counter may wrap anywhere between them, but the whole period is shorter than one wrap.

Return the duty cycle in permille (tenths of a percent), rounded to the nearest integer. If the period is zero, return 0.

Starter code

uint16_t duty_permille(uint16_t rise1, uint16_t fall, uint16_t rise2) {
  return (fall - rise1) * 1000 / (rise2 - rise1);
}

Example tests

A quarter duty cycle

printf("%u\n", duty_permille(0, 250, 1000));

Expected output:

250

Rounds to nearest

printf("%u\n", duty_permille(1000, 1002, 1003));

Expected output:

667

Learn it first

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

More Timers and PWM problems