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:
5555544444Four different duties
softpwm_t p = { { 1, 2, 3, 4 }, 0 };
period(&p);Expected output:
FEC8000000Learn 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.
- 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.