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 ...

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) ...

[STM32] How to configure Timer 1, Channel 3 is PWM 1kHz, duty cycle 20% to control BLDC motor

 To configure Timer1 for a 1 kHz PWM signal with a 20% duty cycle on an STM32H7S3L8 microcontroller, follow these steps: 1. Understand the Timer Parameters PWM Frequency : 1 kHz → Period = 1 ms. Duty Cycle : 20% → ON time = 0.2 ms. The timer’s clock frequency is derived from the APB clock (e.g., TIMCLK). Let’s assume you know the APB clock frequency. The Timer prescaler and auto-reload register (ARR) define the PWM frequency. 2. Compute Timer Parameters Formula: PWM Frequency = Timer Clock (Prescaler + 1) * (ARR + 1) \text{PWM Frequency} = \frac{\text{Timer Clock}}{\text{(Prescaler + 1) * (ARR + 1)}} PWM Frequency = (Prescaler + 1) * (ARR + 1) Timer Clock ​ For 1 kHz PWM: A R R = Timer Clock PWM Frequency ∗ ( Prescaler + 1) − 1 ARR = \frac{\text{Timer Clock}}{\text{PWM Frequency} * (\text{Prescaler + 1)}} - 1 A RR = PWM Frequency ∗ ( Prescaler + 1) Timer Clock ​ −...