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.
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 namedmy_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 thatapp_easy_timer
is a one-shot timer. The maximum timer duration that can be set inapp_easy_timer()
is4194300
which translates to 41943 seconds or 11.7 hours.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); }
Build the project and load it onto target
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