timer in a class

kyrpav
Posts: 37
Joined: Wed Jan 29, 2020 8:27 am

timer in a class

Postby kyrpav » Fri Feb 11, 2022 6:39 am

Is there a proper way to initialise a timer inside a class?

I am trying to do a c++ project and i want to user the high resolution timer.
The class is about XH711 adc 24 bit.

I have an init function where i do everything needed for the adc and i want in there to init also the timer by seting the
esp_timer_create_args_t

When i set the callback function i also set a class function for the callback. I always get error on build

Code: Select all

"void (Xh711::*)(void *args)" cannot be used to initialize an entity of type "esp_timer_cb_t"
and my setup of args is

Code: Select all

    const esp_timer_create_args_t timerArgs={
        .callback = onTimer,
        .arg = NULL,
        .dispatch_method = ESP_TIMER_TASK,
        .name = "Measurement",
        .skip_unhandled_events = false
    };
When i also tried this:

Code: Select all

    const esp_timer_create_args_t timerArgs={
        .callback = Xh711::onTimer,
        .arg = NULL,
        .dispatch_method = ESP_TIMER_TASK,
        .name = "Measurement",
        .skip_unhandled_events = false
    };
   
and i get error of:

Code: Select all

cannot convert 'Xh711::onTimer' from type 'void (Xh711::)(void*)' to type 'esp_timer_cb_t' {aka 'void (*)(void*)'}
What is the proper way to do this?

ESP_Sprite
Posts: 9709
Joined: Thu Nov 26, 2015 4:08 am

Re: timer in a class

Postby ESP_Sprite » Fri Feb 11, 2022 9:19 am

You need to use a static class member, that will match the prototype of the C callback. Static class members don't have a specific object associated with them (no notion of 'this') so you need to use the .arg pointer to pass 'this' to that function; in that static class member function, you can then cast it back to an object and do the things you need to do.

Who is online

Users browsing this forum: Bing [Bot] and 300 guests