Course contentsShow
← Embedded Systems & Computer Architecture
Lesson 256 of 9363. Microcontroller Fundamentals and Bare-Metal CFree lesson

Implementing Pulse Width Modulation for Signal Output

Configure timer output compare registers to generate variable duty cycle signals for controlling external hardware like LEDs or motors.

In this lesson, you will learn how to leverage timer output compare registers to generate a Pulse Width Modulation (PWM) signal for controlling the brightness of an LED or the speed of a motor.

The Core Concept

While we have previously used timers to generate simple delays by polling the counter register, PWM takes our hardware timers to the next level. Instead of just tracking time, we use the timer to toggle a GPIO pin automatically.

To achieve this, we use two registers:

  1. Auto-Reload Register (ARR): Sets the total period of the signal (how fast the timer resets).
  2. Output Compare Register (CCR): Sets the "threshold" or duty cycle.

Think of the timer as a runner on a circular track. The ARR is the length of the track. The CCR is a "gate" placed somewhere on that track. When the timer starts at zero, the GPIO pin is set to high. As the counter increments, it is constantly compared to the value in the CCR. When the counter reaches the CCR value, the hardware automatically flips the GPIO pin to low. When the counter hits the ARR, the timer resets to zero, the pin goes high again, and the cycle repeats.

Implementation Logic

By modifying the value in the CCR register while the timer is running, you change the amount of time the signal remains high within each period. This is the definition of a variable duty cycle.

// Conceptually configuring a timer for PWM
// Assume Timer_Period is the value for ARR, and Duty_Cycle is for CCR
*TIMER_ARR_REG = 1000;  // Total period of 1000 clock ticks
*TIMER_CCR_REG = 250;   // Pin stays high for 250 ticks (25% duty cycle)

// To dim the LED, simply update the CCR register:
*TIMER_CCR_REG = 50;    // LED gets dimmer

By connecting an LED to the pin driven by this timer, the rapid switching—faster than the human eye can perceive—results in a perceived change in brightness rather than a flicker. Similarly, a motor will respond to the average power delivered by this signal, allowing for precise speed control.

Key Takeaway: PWM turns a timer into a hardware-automated signal generator by using the Output Compare Register to define when a GPIO pin switches states within the timer’s period.