Simvik

Software PWM

Drive four PWM channels from a timer tick on pins without PWM hardware. A medium embedded C problem (Timers and PWM), run and graded in the browser.

medium · Timers and PWM · pwm · timers

When there are more LEDs to dim than PWM pins, a timer interrupt can do it in software. Each tick it compares a counter with every channel's duty value.

softpwm_tick(p) returns the outputs for this tick as a bit mask (bit i for channel i): a channel is on while counter < duty[i]. Then the counter advances, wrapping from SOFTPWM_STEPS - 1 back to 0. A duty of SOFTPWM_STEPS or more is always on, and 0 is always off.

Starter code

uint8_t softpwm_tick(softpwm_t *p) {
  uint8_t mask = 0;
  for (int i = 0; i < 4; i++) if (p->duty[i] > 0) mask |= (uint8_t)(1u << i);
  return mask;
}

Example tests

Half on, and always on

softpwm_t p = { { 5, 0, 10, 0 }, 0 };
period(&p);

Expected output:

5555544444

Four different duties

softpwm_t p = { { 1, 2, 3, 4 }, 0 };
period(&p);

Expected output:

FEC8000000

Learn it first

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

More Timers and PWM problems