Interrupts
- C course
- Expert
- Lesson 39/47
- 5 min
Learn interrupt handling.
What is an interrupt?
An interrupt is hardware immediately alerting the processor. When an event occurs (timer expired, button pressed), the processor leaves its current work and jumps to an interrupt service routine (ISR).
An ISR must be short and fast: long operations delay other interrupts. In C an ISR is typically a void function taking no parameters. In embedded systems the ISR sets a flag; the main loop checks this flag and does the real work. This pattern keeps the ISR short. The flag must always be volatile: both the ISR and the main loop access it.
The ISR and flag pattern
Communication between the ISR and the main loop is done via a flag. When the ISR fires it sets the flag: void irq_handler(void) { irq_flag = 1; }. The main loop checks the flag: if (irq_flag) { ... irq_flag = 0; }.
If the flag is not cleared, the main loop re-does the work every time the ISR fires. So after the work is done, the flag is cleared. The flag must be volatile: the compiler must not optimize away the if (irq_flag) check in the main loop. This pattern is the foundation of interrupt handling in embedded C. Slow operations like printf are never done inside an ISR; only the flag is set.
Practice Write an interrupt simulation
Define volatile int irq_flag = 0;. Write void irq_handler(void) that sets irq_flag = 1;. In int main(void) call irq_handler(), then print the flag with printf("Kesme: %d\n", irq_flag).
Starter code
#include <stdio.h>
// volatile bayrak tanımla
// irq_handler fonksiyonu yaz
// main'de çağır ve yazdırSample solution
#include <stdio.h>
volatile int irq_flag = 0;
void irq_handler(void) {
irq_flag = 1;
}
int main(void) {
irq_handler();
printf("Kesme: %d\n", irq_flag);
return 0;
}Expected output
Kesme: 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match interrupt concept
| Term | Meaning |
|---|---|
Interrupt |
Hardware event |
ISR |
Service routine |
Flag |
volatile |
Vector |
ISR address |
2 Complete the interrupt flag's initial value
volatile int irq_flag = ____;
volatile int irq_flag = 0;
Explanation: The flag starts at zero; it becomes 1 when an interrupt fires.
3 Which operation should not be done inside an ISR?
- Setting a flag
- Incrementing a counter
- Reading a register
- A long printf call Correct answer
Explanation: An ISR must be short; a long printf is not done in an ISR.