9. Implementing a Timer

Most applications require timers. In the following section, we will add a simple timer that turns off the LED that we implemented in the previous section. We will turn it off 2 seconds after a BLE connection has been established.

  1. In the in the function user_on_connection() of user_empty_peripheral_template.c, add the following statement to start a timer. Our timer will time out after 2 seconds and then call a function named my_timer_cb():

    app_easy_timer(200, my_timer_cb);
    

    Timer duration

    Note that the timer duration is provided as a multiple of 10 ms, so a value of 200 results in 2000 ms or 2 seconds duration. Also note that app_easy_timer is a one-shot timer. The maximum timer duration that can be set in app_easy_timer() is 4194300 which translates to 41943 seconds or 11.7 hours.

  2. We can now implement our timer handler right above the user_on_connection() function in user_empty_peripheral_template.c as follows:

    void my_timer_cb()
    {
       control_LED(false);
    }
    
  3. Build the project and load it onto target

  4. Use your BLE explorer app to connect to the device and observe that the LED turns off 2 seconds after a BLE connection has been established (The LED will not turn on if you press the button down when the connection is established!)

Note

The call to app_easy_timer_cancel_all() or app_easy_timer_cancel(const timer_hnd timer_id) returns a handle that you can use if you need to cancel a running timer