What is Interrupt in Embedded C: Explanation and Example
Embedded C, an interrupt is a signal that temporarily stops the main program to run a special function called an interrupt service routine (ISR). It helps the microcontroller respond quickly to important events without waiting for the main program to check them.How It Works
Imagine you are reading a book but someone taps your shoulder to tell you something important. You stop reading, listen to them, then go back to your book. An interrupt works the same way in embedded systems. The microcontroller runs its main program but pauses immediately when an interrupt signal arrives.
This pause lets the microcontroller run a small special function called an Interrupt Service Routine (ISR) to handle the event, like reading a sensor or responding to a button press. After the ISR finishes, the microcontroller returns to where it left off in the main program.
Example
This example shows how to use an interrupt in Embedded C to toggle an LED when a button is pressed.
#include <avr/io.h> #include <avr/interrupt.h> // Interrupt Service Routine for external interrupt INT0 ISR(INT0_vect) { PORTB ^= (1 << PORTB0); // Toggle LED connected to PORTB0 } int main(void) { DDRB |= (1 << DDB0); // Set PORTB0 as output (LED) DDRD &= ~(1 << DDD2); // Set PORTD2 as input (button) PORTD |= (1 << PORTD2); // Enable pull-up resistor on button pin EICRA |= (1 << ISC01); // Trigger INT0 on falling edge EIMSK |= (1 << INT0); // Enable external interrupt INT0 sei(); // Enable global interrupts while (1) { // Main loop does nothing, LED toggles on button press via ISR } return 0; }
When to Use
Use interrupts when your embedded system must react quickly to events like button presses, sensor signals, or communication data without wasting time checking them constantly.
For example, in a home alarm system, an interrupt can detect a door opening instantly and trigger an alarm. In a data logger, interrupts can capture sensor data at precise times without delaying other tasks.
Key Points
- An interrupt pauses the main program to run a special function called ISR.
- ISRs handle urgent tasks quickly and then return control to the main program.
- Interrupts help improve responsiveness and efficiency in embedded systems.
- Use interrupts for events like button presses, sensors, or communication signals.