Skip to main content

Function pointer and Callback advantages

 



Example: Button Interrupt with Dynamic Callbacks

#include <stdio.h>
#include <stdint.h>

// Define a callback type
typedef void (*ButtonCallback)(void);

// Global variables
volatile uint8_t button_pressed_flag = 0;
ButtonCallback button_callback = NULL;

// ISR: fast, only sets flag
void BUTTON_IRQHandler(void) {
    button_pressed_flag = 1;
}

// Register a callback dynamically
void register_button_callback(ButtonCallback cb) {
    button_callback = cb;
}

// Two possible actions
void turn_on_led(void) {
    printf("LED turned ON!\n");
}

void send_message(void) {
    printf("Message sent!\n");
}

int main() {
    // At runtime, we can decide which action to use
    int user_choice;

    while (1) {
        printf("Choose action: 1=LED, 2=Message: ");
        scanf("%d", &user_choice);

        if (user_choice == 1)
            register_button_callback(turn_on_led);  // set LED action
        else
            register_button_callback(send_message); // set message action

        // Simulate button press
        BUTTON_IRQHandler();

        // Handle button press safely outside ISR
        if (button_pressed_flag) {
            button_pressed_flag = 0;

            // Here is the **callback in action**
            if (button_callback != NULL) {
                button_callback();  // Calls the function dynamically
            }
        }
    }

    return 0;
}

Key Points Highlighting the Advantage of Callbacks

Aspect Without Callback With Callback
ISR behavior Hardcoded to one action ISR stays fast; action is dynamic
Changing behavior Must edit ISR code Change button_callback at runtime
Flexibility Low — each ISR tied to one function High — ISR works for any registered function
Heavy processing Can block ISR if inside Run safely outside ISR via callback

Why we use callback here:

  • We can change the button behavior at runtime without touching the interrupt code.

  • The ISR stays short and safe, even if the actions are complex.

  • The system becomes modular and reusable: the same button can do different things in different program contexts.


Comments

Popular posts from this blog

[Git] Handle trailing space when patching with git

After complete coding one module in development branch. Next phase is merging. Obviously, you can merge source code automatically without no errors happen. However, life is not dream. Create a patch git diff HEAD > newTariff.patch Apply patch git apply newTariff.patch then problem happens Problem git apply newTariff.patch:106: trailing whitespace. patch does not apply Route cause: Nguyên nhân: Do trong source code có những dấu space thừa (ô vuông màu đỏ hình dưới) Some whitespaces is existed in your patch. (red area in below pictures) Fix Clean white space and patch again. Cách khắc phục Xóa những dấu space này đi và thực hiện patch lại Make up after complete coding. Find and clean whitespace before create patch file. Sửa sau khi code xong Kiểm tra sau khi code xong có lỗi này không git diff HEAD --check Prevent whitespace by manually when typing source code Sửa ngay khi đang code =>Bật chức năng hiển thị các dấu whitespace, hoặc remove trailing ...

[GTK] Example of using GtkBox with label and button

[1]Source code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 #include <gtk/gtk.h> void on_window_closed (GtkWidget * window, gpointer data) { gtk_main_quit(); } static void destroy (GtkWidget * widget, gpointer data) { gtk_main_quit(); } static void button_clicked (GtkWidget * button, gpointer data) { g_print( "Button clicked \n " ); } int main ( int argc, char * argv[]) { GtkWidget * window, * label, * box, * button ; gtk_init( & argc, & argv); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW (window), "Test GTK" ); gtk_window_set_default_size (GTK_WINDOW (window), 500 , 200 ); #if 1 //Use gtk3: change 0->1, Use gtk2: keep it is 0 //Using gtk3 box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 5 ); ...

How to test frame buffer in linux

The intended goal of this article is to provide the user with enough information so they can display an image onto a screen of their choosing. How to re-build frame buffer testing application. Base knowledge http://trac.gateworks.com/wiki/OpenEmbedded/Video_Out Frame buffer test application - rebuild fb-test-app step 1: Download soure code ( git installed on your machine and account in git-hub is required) https://github.com/prpplague/fb-test-app Command in git: git init git clone https://github.com/prpplague/fb-test-app.git step 2: Change makefile vi Makefile //open Makefile by vim editor :set nu //show line number replace from line 6 to line 12 by folow code: CC=arm-linux-gnueabi-gcc CFLAGS=-02 -Wall Save change command :wq step 3: Rebuid Type “make” command step 4: Copy execute file to target system by filezilla or something like that step 5: Remote target by root account, change mode of execute file (what copied from host) ...