0
0
Embedded Cprogramming~5 mins

ISR best practices (keep it short) in Embedded C

Choose your learning style9 modes available
Introduction
ISRs handle urgent tasks quickly when hardware signals happen. Following best practices keeps your program fast and reliable.
When a hardware event like a button press or sensor signal needs immediate attention.
When you must respond quickly to data arriving from communication ports.
When you want to avoid missing important signals by checking them often.
When you want to keep your main program running smoothly without delays.
When you need to update shared data safely between ISR and main code.
Syntax
Embedded C
void ISR_Handler(void) {
    // ISR code here
}
Keep ISR code short and fast to avoid blocking other tasks.
Avoid heavy processing or long loops inside ISR.
Examples
Set a simple flag to handle the event later in the main program.
Embedded C
void ISR_ButtonPress(void) {
    buttonPressedFlag = 1; // Set a flag
}
Quickly read data and set a flag for processing outside ISR.
Embedded C
void ISR_UART(void) {
    receivedData = UART_Read();
    dataReadyFlag = 1;
}
Sample Program
This program simulates an ISR setting a flag and the main program checking it to handle the event.
Embedded C
#include <stdio.h>
#include <stdbool.h>

volatile bool buttonPressedFlag = false;

void ISR_ButtonPress(void) {
    buttonPressedFlag = true; // Quick flag set
}

int main() {
    printf("Program started\n");
    // Simulate button press interrupt
    ISR_ButtonPress();

    if (buttonPressedFlag) {
        printf("Button was pressed! Handling event in main.\n");
        buttonPressedFlag = false; // Reset flag
    }

    return 0;
}
OutputSuccess
Important Notes
Never call slow functions like printf inside ISR.
Use volatile keyword for variables shared between ISR and main code.
Disable interrupts only if absolutely necessary and keep that time very short.
Summary
Keep ISR code short and simple.
Use flags or buffers to communicate with main code.
Avoid heavy processing or blocking calls inside ISR.