Course contentsShow
← Embedded Systems & Computer Architecture
Lesson 279 of 9364. Peripheral Interfacing and ControlFree lesson

Generating Pulse Width Modulation Signals

Learners will manipulate output compare registers to generate variable duty cycle square waves for controlling motors, LEDs, and power converters.

Mastering Variable Duty Cycles with Output Compare

In this lesson, you will learn how to manipulate Output Compare registers to create variable duty cycle signals for precise control of motors and LEDs.

While we previously used hardware timers to create simple periodic toggles, we often need finer control over the "on" time of a signal—this is the essence of Pulse Width Modulation (PWM). To achieve this, we shift our focus from simple overflow interrupts to Output Compare (OC) units.

How Output Compare Works

An Output Compare unit monitors the timer’s counter register. You define a "threshold" value in an Output Compare Register (OCR). As the timer counts up, the hardware continuously compares the counter value to the OCR value. When they match, the peripheral automatically triggers a change in the state of the associated GPIO pin—such as flipping it from high to low.

By combining this with the Timer's Auto-Reload Register (which defines the total period), you create a "window" of time. By changing the value in the OCR, you determine exactly when, within that window, the signal switches state.

Implementation Concept

If your timer counts from 0 to 100 (your Auto-Reload value), and you set your Output Compare Register to 25, the pin will be "on" for the first 25 ticks and "off" for the remaining 75. This gives you a 25% duty cycle.

// Simplified logic for a timer peripheral
// Total period (100 ticks)
TIMER_AutoReload = 100; 

// 25% duty cycle: set compare match at 25
TIMER_OutputCompareRegister = 25; 

// Pin output stays HIGH until count hits 25, then drops LOW
// Pin resets to HIGH when timer wraps around to 0

By dynamically updating the TIMER_OutputCompareRegister in your main loop or an interrupt, you can smoothly vary the brightness of an LED or adjust the speed of a motor. This approach is highly efficient because the hardware handles the signal timing entirely in the background, freeing your CPU from the overhead of manually toggling pins.

Key Takeaway: By adjusting the Output Compare Register relative to the Auto-Reload period, you can precisely control the duty cycle of a signal without taxing the CPU.