Skip to content

PWM — hardware-generated waveforms

Learning goals

Explain duty cycle, configure hardware PWM, compare Assembly and C register setup, and distinguish simulated timer behavior from physical waveform measurements.

Prerequisites

Complete Timers and interrupts and understand timer modes, prescalers and output compare.

Pulse-width modulation (PWM) lets a timer peripheral generate a repeating digital waveform while the CPU performs other work.

Duty cycle

duty cycle = high time / period

A 25% duty cycle is high for one quarter of each period; 75% is high for three quarters.

Why use the timer?

A software loop can toggle a pin, but its timing consumes CPU time and changes when other code runs. Hardware PWM is generated by timer/output-compare hardware after configuration.

The CPU normally configures waveform generation mode, timer clock/prescaler, compare output mode, compare value and output-pin direction.

ASM ↔ C

Configure the same PWM mode first through explicit AVR register operations in Assembly, then in C. Disassemble the C version and identify the writes corresponding to each datasheet step.

Under the hood

Relate the C register expressions to the resulting load/store and bit-manipulation instructions. Identify which operations configure the peripheral once and which operation changes duty cycle at runtime.

Try it

Build the C and Assembly variants, compare their register configuration, then change the compare value and observe the modeled timer state.

Expected result

You can connect the selected PWM mode, prescaler and compare value to the expected modeled duty cycle.

Qualification

Q1 verifies register configuration, instruction flow and modeled timer/output-compare behavior. The automated paired C/Assembly test observes OC0A/PB3 edges through simavr and measures the resulting duty cycle, requiring the configured approximately 25% waveform. Q2 is required for claims about voltage waveform, frequency accuracy, rise/fall behavior, LED brightness or instrument measurements.

Check your understanding

  1. Why is hardware PWM preferable to a busy-loop for many applications?
  2. What determines duty cycle?
  3. Which register change can alter duty cycle without rebuilding the complete timer configuration?
  4. Why do physical waveform claims require Q2?

Next

Continue to USART.