This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

Best way to reload an app timer with a new value?

Currently, I'm using the following:

if((err_code = app_timer_stop(m_timer_id)) == NRF_SUCCESS)
{
    err_code = app_timer_start(m_timer_id, APP_TIMER_TICKS(g_timer_val*1000, APP_TIMER_PRESCALER), NULL);
    APP_ERROR_CHECK(err_code);
}
else
{
    APP_ERROR_CHECK(err_code);
}

The problem is that most of the time, the above code is called from various handlers and ISRs which have a higher priority than SWI0 (which is used to update the timer task list). So the timer list update actually occurs after the ISR calling the above code returns.

Due to all this, the new timer value doesn't actually get loaded into the timer. I'm pretty sure this is because the stop timer action doesn't get performed.

In short, does anyone have any ideas on how a app timer value can be updated while it is running?

Thanks.

  • The solution to this is to use the event scheduler so that the timer actually stops before it is re-started (as app_timer_stop and app_timer_start will now be executed from the main context).

    Event function:

    void reset_idle_timer_event(void * p_event_data, uint16_t event_size)
    {
    reset_idle_timer();
    }
    

    Scheduling event:

    // Reset idle timer
    err_code = app_sched_event_put(NULL, NULL, reset_idle_timer_event);
    APP_ERROR_CHECK(err_code);
    

    Reset timer function:

    void reset_idle_timer(void)
    {
        uint32_t err_code;
        
        // Stop timer
        err_code = app_timer_stop(m_idle_timer_id);
        APP_ERROR_CHECK(err_code);
    
        // Start timer
        err_code = app_timer_start(m_idle_timer_id, APP_TIMER_TICKS(idle_timer_val*1000, APP_TIMER_PRESCALER), NULL);
        APP_ERROR_CHECK(err_code);
    }
    
Related