In this lesson, you will learn how to measure the precise time between a hardware trigger and the execution of your Interrupt Service Routine (ISR), and how to stabilize that timing.
Understanding Latency and Jitter
When an external event occurs—like a sensor signal hitting an input pin—the CPU doesn't start your code instantly. Interrupt Latency is the delay between that hardware signal and the very first instruction inside your ISR. This delay exists because the processor must finish its current instruction, push register states onto the stack, and look up the address in the vector table.
Jitter is the variation in this latency. If your latency is sometimes 2 microseconds and sometimes 10 microseconds, your system has high jitter, which ruins precise timing tasks like motor control or sampling.
Measuring the Delay
The most reliable way to measure this is using a GPIO pin and an oscilloscope:
- Set a GPIO pin to
HIGHat the exact moment the hardware event occurs (e.g., via a timer match). - Set that same GPIO pin to
LOWat the very first line of your ISR. - Use an oscilloscope to measure the width of the resulting pulse. That width is your exact latency.
// Inside your ISR
void GPIO_Handler(void) {
// 1. Toggle pin LOW immediately upon entry
GPIO_PIN_LOW(DEBUG_PORT, PIN_0);
// 2. Perform your time-critical task
ProcessSensorData();
}
Optimizing for Consistency
To minimize jitter, you must ensure the execution path is predictable:
- Disable Nested Interrupts: If a lower-priority interrupt fires while the CPU is preparing to enter your high-priority ISR, it adds variable delay.
- Keep ISRs Short: Avoid heavy logic inside the ISR. If you must process data, set a flag and return to the mainline to handle it.
- Use Tightly Coupled Memory: If your architecture allows, store your ISR code in faster RAM rather than slower Flash to ensure consistent fetch times.
By reducing the amount of work the CPU does before reaching your ProcessSensorData() line, you shrink both the average latency and the variance (jitter) between events.
Key Takeaway: Interrupt latency is the unavoidable overhead of hardware context switching, while jitter is the unwanted variation in that delay caused by competing interrupts and branching paths; keep ISRs lean to keep timing deterministic.