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

Executing Time-Triggered Output State Changes

Learners will use output compare match events to toggle digital pins at precise intervals, independent of software execution latency.

In this lesson, you will learn how to use hardware output compare match events to toggle digital pins at precise, jitter-free intervals that remain independent of software execution delays.

The Problem with Software-Based Timing

Up until now, you have likely toggled pins by writing to a GPIO register within a software loop or an interrupt service routine (ISR). While this works for simple tasks, it is subject to "latency." If your processor is busy handling a high-priority interrupt or performing a complex calculation, your pin toggle will be delayed. This creates jitter, where the interval between state changes is inconsistent.

The Hardware Solution: Output Compare

To achieve absolute precision, we offload the timing responsibility to the Timer peripheral’s Output Compare (OC) unit. Instead of waiting for code to tell the pin to flip, we configure the hardware to do it for us.

  1. Set the Threshold: You load a specific value into the timer’s Compare Register (often called OCR or CCRx).
  2. Hardware Comparison: The timer counter constantly increments. The hardware logic compares this counter to your threshold value in real-time.
  3. Automatic Action: When the counter matches your threshold, the hardware automatically triggers a "match event." Instead of just firing an interrupt, the timer is configured to physically toggle the connected GPIO pin directly.

Conceptual Implementation

Consider this conceptual setup where the hardware handles the toggle:

// Configure Timer to toggle the pin on Match
Timer_Config_Compare(TIMER1, CHANNEL_A, MODE_TOGGLE);

// Set the threshold for 1000 clock cycles
Timer_Set_Compare_Value(TIMER1, CHANNEL_A, 1000);

// The hardware now takes over:
// Every time the timer hits 1000, the pin flips state.
// No CPU intervention is required for the actual toggling.

By using this approach, the GPIO pin state change is synchronized to the timer's clock signal. The CPU is completely freed from managing the timing, and because the toggle occurs at the exact moment the hardware comparator triggers, you eliminate software-induced jitter entirely. This technique is the foundation for generating reliable, high-frequency square waves and precise clock signals for external hardware.

Key Takeaway: Output compare hardware allows you to trigger pin state changes at exact, deterministic intervals by bypassing software execution latency entirely.