An ISR is a special function that runs automatically when a hardware event happens. It helps your program respond quickly without waiting.
0
0
Writing an ISR (Interrupt Service Routine) in Embedded C
Introduction
When a button is pressed and you want to react immediately.
When a timer reaches zero and you need to update something.
When data arrives on a communication port and you want to read it right away.
When a sensor triggers an alert and you want to handle it fast.
Syntax
Embedded C
void ISR_Name(void) __interrupt (interrupt_number) {
// code to handle interrupt
}The function name can be anything but must match the interrupt vector.
The __interrupt keyword tells the compiler this is an ISR.
Examples
This ISR runs when Timer0 interrupt occurs (interrupt number 1).
Embedded C
void Timer0_ISR(void) __interrupt (1) {
// handle Timer0 interrupt
}This ISR runs when external interrupt 0 happens (interrupt number 0).
Embedded C
void External0_ISR(void) __interrupt (0) { // handle external interrupt 0 }
Sample Program
This program uses Timer0 interrupt to increase a counter every time the timer overflows. The ISR runs automatically when the timer interrupt occurs.
Embedded C
#include <reg51.h> volatile unsigned int count = 0; void Timer0_ISR(void) __interrupt (1) { count++; // Increase count every timer interrupt TH0 = 0x3C; // Reload timer high byte TL0 = 0xB0; // Reload timer low byte } void main() { TMOD = 0x01; // Timer0 mode 1 (16-bit) TH0 = 0x3C; // Load timer high byte TL0 = 0xB0; // Load timer low byte ET0 = 1; // Enable Timer0 interrupt EA = 1; // Enable global interrupts TR0 = 1; // Start Timer0 while(1) { // Main loop does nothing, count updates in ISR } }
OutputSuccess
Important Notes
ISRs should be short and fast to avoid delaying other interrupts.
Do not use functions like printf inside an ISR because they take too long.
Remember to clear interrupt flags if your hardware requires it to avoid repeated interrupts.
Summary
ISRs run automatically when hardware events happen.
Use __interrupt keyword to define an ISR in embedded C.
Keep ISR code short and simple for fast response.