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

Generating Square Waves Using Timer Compare Registers

Learners will configure hardware timers to toggle output pins automatically upon reaching specific count values to establish basic pulse trains.

Generating Square Waves Using Timer Compare Registers

In this lesson, you will learn how to generate precise square waves by configuring hardware timers to automatically toggle a physical output pin the moment the timer's counter value matches a predefined compare register value.

The Mechanism of Hardware Toggling

Previously, we used periodic interrupts to toggle pins via software. While effective, this consumes CPU cycles and is susceptible to "interrupt latency"—the delay between the timer event and the CPU execution. A more efficient approach is to use the Output Compare feature.

Inside the timer peripheral, there is a dedicated hardware comparator. You load a specific value into the Compare Register (CCR). As the timer's main counter increments, the hardware continuously compares the two values. When they match, the timer peripheral can be configured to automatically flip the logic state of a connected GPIO pin. Because this happens entirely in hardware, the CPU remains free to perform other tasks, and the square wave exhibits near-zero jitter.

Configuration Logic

To generate a square wave with a 50% duty cycle, you configure the timer to trigger a state change upon every match. Here is the conceptual setup for such a peripheral:

// Conceptual setup for a toggle-on-match output
void configure_square_wave(uint32_t frequency_hz) {
    // 1. Set the Timer Period (Auto-Reload)
    // Determines the total cycle length
    TIMER->ARR = (SystemClock / frequency_hz);
    
    // 2. Set the Compare Register
    // Half the ARR value creates a 50% duty cycle
    TIMER->CCR1 = (TIMER->ARR / 2);
    
    // 3. Configure Output Mode
    // Set pin to "Toggle on Match" (hardware-controlled)
    TIMER->CCMR1 |= TIMER_TOGGLE_ON_MATCH;
    
    // 4. Enable Output
    TIMER->CCER |= ENABLE_OUTPUT_PIN;
}

By leveraging this hardware feature, the output pin transitions from high to low (and vice-versa) at exact, hardware-timed intervals. This produces a clean, consistent square wave regardless of how busy the CPU is with other interrupts or task scheduling.

Key Takeaway: Using hardware timer compare registers allows you to generate high-precision square waves by offloading the toggle logic from the CPU to the peripheral hardware, ensuring zero-latency transitions.