logitech mouse logitech mouse - 9 months ago 50
C Question

RTC initialisation in an MCU - why use a global callback

The code below is related to the initialization of an RTC in an MCU.

Would anybody know the rational for passing

and then setting a global callback
equal to it.

Why would you use a global callback at all when there is an other function called
defined and used as the callback in the struct.

int main() {

void ( * global_rtc_cb)(void *);

int rtc_init(void (*cb)(void *)) {
rtc_config_t cfg;

cfg.init_val = 0;
cfg.alarm_en = true;
cfg.alarm_val = ALARM;
cfg.callback = rtc_callback;
cfg.callback_data = NULL;

global_rtc_cb = cb;

irq_request(IRQ_RTC_0, rtc_isr_0);
rtc_set_config(QM_RTC_0, &cfg);

return 0;

* RTC configuration type.
typedef struct {
uint32_t init_val; /**< Initial value in RTC clocks. */
bool alarm_en; /**< Alarm enable. */
uint32_t alarm_val; /**< Alarm value in RTC clocks. */

* User callback.
* @param[in] data User defined data.
void (*callback)(void *data);
void *callback_data; /**< Callback user data. */
} rtc_config_t;

Answer Source

The rtc_ functions are part of the RTC driver. The RTC driver has something driver-specific to do when the event that prompts the callback occurs. This driver-specific stuff happens in rtc_callback. But there may also be other application-specific stuff that the application must do when the event occurs. The application-specific stuff should be done at the application layer, not within the driver. So if the application has something to do in response to the event it can provide a callback to rtc_init. Surely rtc_callback calls global_rtc_cb so that both the driver-specific stuff and the application-specific stuff is performed when the event occurs. Apparently your particular application doesn't need to do anything for this event so it passes NULL to rtc_init. But a different application that uses the same driver may provide a callback function.