0
0
Embedded Cprogramming~5 mins

Polling vs interrupt-driven execution in Embedded C

Choose your learning style9 modes available
Introduction

Polling and interrupt-driven execution are two ways a program can check for and respond to events. They help the program know when something important happens.

When you want to keep checking a sensor regularly to see if it changed.
When you want the program to do other tasks and only respond when a button is pressed.
When you want to save power by letting the processor sleep until something happens.
When you need fast response to an event without waiting.
When your program is simple and can afford to check events in a loop.
Syntax
Embedded C
/* Polling example */
while(1) {
    if (event_flag) {
        handle_event();
        event_flag = 0;
    }
}

/* Interrupt-driven example */
void ISR() {
    handle_event();
}

int main() {
    enable_interrupts();
    while(1) {
        // main tasks
    }
}

Polling uses a loop to check for events repeatedly.

Interrupt-driven uses special functions called ISRs that run automatically when events happen.

Examples
The program keeps checking if the button is pressed and turns on the LED when it is.
Embedded C
/* Polling: Check button press in a loop */
while(1) {
    if (button_pressed()) {
        turn_on_led();
    }
}
The LED turns on automatically when the button is pressed, without checking in the loop.
Embedded C
/* Interrupt-driven: Button press triggers ISR */
void button_ISR() {
    turn_on_led();
}

int main() {
    enable_button_interrupt();
    while(1) {
        // other tasks
    }
}
Sample Program

This program simulates checking for an event in a loop. Every two loops, it sets an event flag. When the flag is set, it handles the event and clears the flag.

Embedded C
/* Simple polling example */
#include <stdio.h>
#include <stdbool.h>

bool event_flag = false;

void handle_event() {
    printf("Event handled!\n");
}

int main() {
    int counter = 0;
    while(counter < 5) {
        // Simulate event every 2 loops
        if (counter % 2 == 0) {
            event_flag = true;
        }

        if (event_flag) {
            handle_event();
            event_flag = false;
        }
        counter++;
    }
    return 0;
}
OutputSuccess
Important Notes

Polling can waste CPU time if events are rare because it keeps checking.

Interrupts let the CPU do other work or sleep until an event happens, saving power.

Interrupts need careful programming to avoid conflicts and bugs.

Summary

Polling checks for events repeatedly in a loop.

Interrupt-driven execution responds to events automatically using special functions.

Use polling for simple or fast-check needs; use interrupts for efficient and responsive programs.