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:
250Full duty at the longest period
printf("%u\n", pwm_compare(65535, 100));Expected output:
65535Learn 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
- Drive a GPIO pin · Set or clear one pin in a port's output data register.
- Read a GPIO pin · Report the level on one input pin.
- Configure a pin mode · Write a 2-bit mode field for one pin of a port.
- Atomic pin write · Change a pin with a single write to the bit set/reset register.
- Hygienic register macros · Fix four bit-manipulation macros that break on compound arguments.
- Clear a write-1-to-clear flag · Acknowledge one interrupt flag without wiping the others.
- Poll with a timeout · Wait for a status bit, but never forever.
- UART baud-rate divisor · Compute the divisor that gives the closest baud rate.
- Lay out a register map · Declare a peripheral struct whose members land on the right offsets.
- ADC conversion sequence · Write a 5-bit channel number into a computed slot of a register.
- Read a split counter · Read a 32-bit count from two 16-bit halves that keep changing.
- Fix: disabling one interrupt silences the timers · Clearing one bit of an interrupt-enable register clears every bit below it as well.
- Infusion pump: read the pressure, with a timeout · Start a conversion, poll its done flag, and give up safely if the converter never answers.