Fix: 100 % brightness still flickers
A duty-cycle conversion uses the auto-reload value instead of the period length. An easy embedded C problem (Timers and PWM), run and graded in the browser.
easy · Timers and PWM · find-the-bug · pwm · off-by-one
Bug report. duty_to_ccr(percent) converts a duty cycle from 0 to 100 % into the compare value for the PWM channel under Provided. At 100 % the LED strip still flickers faintly, and every other setting is slightly dim compared with the spec. Fix it by changing one line.
Starter code
uint32_t duty_to_ccr(unsigned percent) {
return PWM_ARR * percent / 100;
}Example tests
Off, half and full
printf("%u %u %u\n", duty_to_ccr(0), duty_to_ccr(50), duty_to_ccr(100));Expected output:
0 500 1000Learn 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.
- 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.
- 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.