nRF5 SDK v12.1.0
Timer library

The timer library enables the application to create multiple timer instances based on the RTC1 peripheral. Checking for time-outs and invoking the user time-out handlers is performed in the RTC1 interrupt handler. List handling is done using a software interrupt (SWI0). Both interrupt handlers are running in APP_LOW priority level.

Usage

Use the macro APP_TIMER_INIT to initialize the library. This macro allocates memory for internal queues and performs the library initialization. Because of the memory initialization, it should not be called more than once. During initialization, you can provide a pointer to a scheduler function that will be called when any timer expires. This function can forward the handling of timer expiration to a different context.

APP_TIMER_INIT(PRESCALER, OP_QUEUE_SIZE, scheduler_function)

To define a timer, use the APP_TIMER_DEF macro. This macro allocates memory for the timer instance and declares an identifier that can later on be used to refer to the specific instance. Before starting a timer, the timer must be created.

APP_TIMER_DEF(my_timer_id);
err_code = app_timer_create(&my_timer_id, mode, timeout_handler)

After the timer is created, it can be controlled using app_timer_start and app_timer_stop.

When calling app_timer_start() or app_timer_stop(), the timer operation is just queued, and the software interrupt is triggered. The actual timer start/stop operation is executed by the SWI0 interrupt handler. Since the SWI0 interrupt is running in APP_LOW, if the application code calling the timer function is running in APP_LOW or APP_HIGH, the timer operation will not be performed until the application handler has returned. This will be the case, for example, when stopping a timer from a time-out handler when not using the scheduler.

To use the library with the Scheduler, use a thin wrapper (app_timer_appsh).

Migration note

When migrating to SDK version 12.0.0, keep in mind that some changes have been introduced to the timer library. It might be necessary to adjust the code of your application to comply with these changes.

  1. app_timer_cnt_get() API change - The counter value is now returned by the function and not by the pointer. Therefore, you must change the following code:
    err_code = app_timer_cnt_get(&counter);
    to:
    counter = app_timer_cnt_get();
  2. The OP_QUEUE_SIZE parameter in the APP_TIMER_INIT macro is now the size of a common operation queue used for all priority levels in the system. Previously, it was the size of separate operation queues used for each priority level. Use the APP_TIMER_WITH_PROFILER option to tune the OP_QUEUE_SIZE value.

Documentation feedback | Developer Zone | Subscribe | Updated