UART interrupt-driven communication in Embedded C - Time & Space Complexity
When using UART with interrupts, we want to know how the program's work changes as more data comes in.
We ask: How does the time spent handling interrupts grow with the amount of data received?
Analyze the time complexity of the following code snippet.
volatile char buffer[BUFFER_SIZE];
volatile int head = 0;
void UART_IRQHandler(void) {
if (UART_Receive_Flag()) {
buffer[head++] = UART_Read_Data();
if (head >= BUFFER_SIZE) head = 0;
}
}
This code handles UART data using an interrupt. Each time data arrives, the interrupt runs and stores one byte in a buffer.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Interrupt handler runs once per received byte.
- How many times: Once for each byte received, repeating as data arrives.
Each new byte causes one interrupt call that does a fixed amount of work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 interrupt calls, 10 buffer writes |
| 100 | 100 interrupt calls, 100 buffer writes |
| 1000 | 1000 interrupt calls, 1000 buffer writes |
Pattern observation: The work grows directly with the number of bytes received.
Time Complexity: O(n)
This means the time spent grows linearly with the number of bytes received.
[X] Wrong: "The interrupt handler runs only once regardless of data size."
[OK] Correct: Each byte triggers its own interrupt, so the handler runs many times, not just once.
Understanding how interrupt-driven code scales helps you write efficient embedded programs and explain your reasoning clearly.
"What if the interrupt handler processed multiple bytes at once instead of one? How would the time complexity change?"