Simvik

PWM compare value

Convert a duty cycle in percent to a timer compare value. An easy embedded C problem (Registers and memory-mapped I/O), run and graded in the browser.

easy · Registers and memory-mapped I/O · timers · pwm · scaling

A timer counts period ticks per PWM cycle, and the output is high while the counter is below the compare value.

Return the compare value for a duty cycle of percent, rounded down. Treat anything above 100 percent as 100.

Starter code

uint16_t pwm_compare(uint16_t period, uint8_t percent) {
  // period * percent / 100, with percent limited to 100.
  return 0;
}

Example tests

Quarter duty

printf("%u\n", pwm_compare(1000, 25));

Expected output:

250

Full duty at the longest period

printf("%u\n", pwm_compare(65535, 100));

Expected output:

65535

Learn it first

  • Registers, volatile and const · How C talks to hardware: memory-mapped registers, what volatile and const promise, register structs and read-modify-write.

More Registers and memory-mapped I/O problems