Interrupt Latency in Embedded C: Definition and Example
interrupt latency is the time delay between when an interrupt is triggered and when the processor starts executing the interrupt service routine (ISR). It includes the time to finish the current instruction and save the processor state before handling the interrupt.How It Works
Imagine you are reading a book and someone suddenly calls your name. You need a moment to finish the sentence you are reading and then turn your attention to the person. In embedded systems, interrupt latency is similar: it is the delay from when an interrupt signal arrives to when the processor actually starts running the interrupt code.
This delay happens because the processor must complete the current instruction and save its current work (like bookmarks in a book) before switching to the interrupt task. The saved state allows the processor to return to where it left off after handling the interrupt.
Example
This example shows a simple embedded C program where an interrupt triggers a function to toggle an LED. The interrupt latency is the time between the interrupt event and the start of the toggle function.
#include <avr/io.h> #include <avr/interrupt.h> volatile int led_state = 0; ISR(INT0_vect) { // Interrupt Service Routine toggles LED if (led_state == 0) { PORTB |= (1 << PORTB0); // Turn LED on led_state = 1; } else { PORTB &= ~(1 << PORTB0); // Turn LED off led_state = 0; } } int main(void) { DDRB |= (1 << DDB0); // Set PORTB0 as output (LED) PORTB &= ~(1 << PORTB0); // LED off initially // Configure external interrupt INT0 on falling edge EICRA |= (1 << ISC01); EICRA &= ~(1 << ISC00); EIMSK |= (1 << INT0); // Enable INT0 interrupt sei(); // Enable global interrupts while (1) { // Main loop does nothing, waiting for interrupts } return 0; }
When to Use
Understanding and minimizing interrupt latency is important in real-time embedded systems where quick responses are critical. For example, in automotive systems, sensors may trigger interrupts that must be handled immediately to ensure safety.
Use interrupt latency knowledge when designing systems that require fast reaction times, such as motor control, medical devices, or communication protocols. Optimizing latency helps avoid delays that could cause system failures or missed events.
Key Points
- Interrupt latency is the delay before the processor starts the interrupt code.
- It includes finishing the current instruction and saving the processor state.
- Lower latency means faster response to important events.
- Critical in real-time and safety-sensitive embedded applications.