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

I have a simple question about App_Timer.

Hello, everyone!

I use SDK v17 and test various functions using App_Timer.  The timer function that I want is to turn the LED on for 5 seconds and then turn off after 5 seconds.
I made a timer that worked for five seconds.
//single timer setting
static void LED_timer_handler(void * p_context)
{
    nrf_gpio_pin_clear(APP_LED_2); //led2 on
    printf("Left LED ON\n");
}

static void timers_init(void)
{
    ret_code_t err_code;

    // Initialize timer module.
    err_code = app_timer_init();
    APP_ERROR_CHECK(err_code);

    // Create LED timers.
    err_code = app_timer_create(&m_LED_timer_id,
                                APP_TIMER_MODE_SINGLE_SHOT, //SINGLE_SHOT or REPEATED //single shot timer
                                LED_timer_handler);   
}


static void LED_timers_start(void)
{
    ret_code_t err_code;

    // Start application timers.
    err_code = app_timer_start(m_LeftLED_timer_id, APP_TIMER_TICKS(5000), NULL); //5sec led on
    APP_ERROR_CHECK(err_code);
    printf("Led Start\n");
}
.
.
.
static void app_button_event_generator(void)
{
  if ((pressed_duration >= 2000) && (pressed_duration < 5000) ){ //press over 2sec

    NRF_LOG_INFO("Button pressed for 2sec...");
    printf("Long button\n");
    LED_timers_start(); //timer test
}
However, this code activates the timer_handler five seconds after pressing the button.
How do I get the LED to turn on as soon as I press the button? And I going to have the LED turn off after the timer is over, and how do we measure the timer or know it's over?
Thank you always for everyone's help.
  • Hi,

    If you want to turn the LED on when the button is pushed, you should move the clearing of the GPIO to the button event handler:

    static void app_button_event_generator(void)
    {
      if ((pressed_duration >= 2000) && (pressed_duration < 5000) ){ //press over 2sec
        nrf_gpio_pin_clear(APP_LED_2); //led2 on
        NRF_LOG_INFO("Button pressed for 2sec...");
        printf("Long button\n");
        LED_timers_start(); //timer test
    }

    Then you can turn it off again in the timer event handler:

    static void LED_timer_handler(void * p_context)
    {
        nrf_gpio_pin_set(APP_LED_2); //led2 off
        printf("Left LED OFF\n");
    }

    The timer handler will trigger when the timer times out. If you want to know if a timer is running, you can set a flag when starting the timer, and clear it in the timer event handler.

    Best regards,
    Jørgen

Related