In this lesson, you will learn how to determine the exact duration of a digital pulse by capturing timestamps at both its rising and falling edges.
The Concept of Dual-Edge Capture
Previously, you learned how to use timers to generate signals (PWM) and measure frequency. Calculating pulse duration is a refinement of this, where we focus on the time elapsed between a logic-high start and a logic-low finish.
To measure a pulse width accurately, we configure our timer’s Input Capture peripheral to "listen" for two specific events on the same GPIO pin:
- Rising Edge: The start of the pulse. When detected, the hardware automatically saves the current timer count into a register.
- Falling Edge: The end of the pulse. When detected, the hardware saves the second timer count.
By subtracting the first captured value from the second, we get the total number of timer "ticks" that occurred while the signal was high. Because we know the timer’s clock frequency (from our work with prescalers), we can convert these ticks into a real-world time value, such as microseconds.
Implementation Logic
Using your knowledge of interrupts, you can handle this asynchronously. When the input pin changes state, an interrupt is triggered. Inside the interrupt service routine, we toggle the edge-detection sensitivity:
void Timer_InputCapture_Handler() {
if (is_rising_edge()) {
start_time = read_timer_value();
configure_edge_detection(FALLING); // Switch to look for the end
} else {
end_time = read_timer_value();
pulse_duration = end_time - start_time;
configure_edge_detection(RISING); // Reset for the next pulse
}
}
By alternating the capture edge, the system "tracks" the pulse as it travels through the logic levels. This approach is highly precise because it relies on hardware timestamps rather than software polling, which would be susceptible to jitter and latency. Whether you are reading a digital sensor or decoding infrared signals, this dual-edge method provides the cycle-accurate measurement required for robust data acquisition.
Key Takeaway: Pulse duration is calculated by capturing two timer snapshots at opposite signal transitions and computing the difference, ensuring high-precision timing regardless of system CPU load.