How to pass data to IoT Button callback (via usr_data void pointer)

flimsy
Posts: 9
Joined: Mon Nov 06, 2023 3:41 am

How to pass data to IoT Button callback (via usr_data void pointer)

Postby flimsy » Tue Feb 06, 2024 10:49 pm

I'm trying to define a set of buttons to control an LED channel via the IoT Button component. My issue is that when the callback gets executed, whatever user data would have been passed in to the callback appears to no longer exist. Even in the case below where I am passing in a reference to a global rotary encoder configuration object, the memory I am trying to access appears to not exist when the button is pressed. Does anyone know the proper way to do this? Optimally I would just pass an integer value indicated which button index was pressed.

Code: Select all

static void button_single_click_cb(void *arg, void *usr_data) {
    RotaryEncoderConfig *config = (RotaryEncoderConfig *)usr_data;
    ESP_LOGI(TAG, "Button %lu single click", config->led_channel_index);
     free(usr_data);
}

void setup_buttons() {
    ESP_LOGI(TAG, "Initializing rotary encoder buttons.");

    for (uint8_t index = 0; index < LEDC_TEST_CH_NUM; index++) {
        button_config_t gpio_btn_cfg = {
            .type = BUTTON_TYPE_GPIO,
            .long_press_time = CONFIG_BUTTON_LONG_PRESS_TIME_MS,
            .short_press_time = CONFIG_BUTTON_SHORT_PRESS_TIME_MS,
            .gpio_button_config = {
                .gpio_num = rotaryEncoderConfigs[index].gpio_sw,
                .active_level = BUTTON_ACTIVE_LEVEL,
            },
        };
        ESP_LOGI(TAG, "Registering button index %d", index);
        button_handle_t gpio_btn = iot_button_create(&gpio_btn_cfg);

        if(NULL == gpio_btn) {
            ESP_LOGE(TAG, "Button create failed");
        } else {
            RotaryEncoderConfig *channel = &rotaryEncoderConfigs[index];
            ESP_LOGI(TAG, "Registering button callbacks for index %d", index);
            iot_button_register_cb(gpio_btn, BUTTON_SINGLE_CLICK, button_single_click_cb, channel);
        }
    }
}

MicroController
Posts: 1736
Joined: Mon Oct 17, 2022 7:38 pm
Location: Europe, Germany

Re: How to pass data to IoT Button callback (via usr_data void pointer)

Postby MicroController » Wed Feb 07, 2024 12:01 am

Do not free(usr_data)!
Optimally I would just pass an integer value indicated which button index was pressed.
You can just pass (void*)intValue as the callback's user data, and get it back via int intValue = (int)usr_data;
Not that I recommend to do this, but it does work.

flimsy
Posts: 9
Joined: Mon Nov 06, 2023 3:41 am

Re: How to pass data to IoT Button callback (via usr_data void pointer)

Postby flimsy » Wed Feb 07, 2024 1:41 am

Ah, of course! That makes total sense, thank you!

Who is online

Users browsing this forum: No registered users and 166 guests