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:
250Rounds to nearest
printf("%u\n", duty_permille(1000, 1002, 1003));Expected output:
667Learn 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.
- 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.