9. Application Timer

In this section, we will implement an application timer to turn the LED, D1, on the daughter card off 2 seconds after a connection has been established.

First, we will prepare a global timer handle that will be retained during sleep. Add the following declaration just below the include directives in main.c:

Code 17 Timer handle declaration
// Timer to turn LED off 2 seconds after connection was established----
__RETAINED static OS_TIMER led_off_timer;

Keeping this timer handle retained would ensure that we could manipulate or stop the timer anywhere in our implementation. We are not actually taking advantage of this here, but it is good coding practice to always prepare for such a need.

Next, we implement the timer callback function to control the LED. We will implement this function just above the connection handler, handle_evt_gap_connected(). Our callback function takes advantage of the LED control function that we implemented earlier:

Code 18 Timer callback function
static void led_off_timer_cb()
{
   led_control(false);
}

Now, all we need to do is to create and start the timer. Modify the connection handler as highlighted below:

Code 19 Connection handler with application timer
static void handle_evt_gap_connected(ble_evt_gap_connected_t *evt)
{
   printf("BLE Connection established: %d \n\r", evt->conn_idx);

   led_control(true);

   // Get the input status of Key1
   bool k1_status = hw_gpio_get_pin_status(KEY1_PORT, KEY1_PIN);

   // Output the status of Key1
   if(k1_status == false)
      puts("Key1 was pressed as the connection was established\n\r");
   else
      puts("Key1 was NOT pressed as the connection was established\n\r");

   // Create and start one-shot timer to turn LED off 2 seconds after a connection was
   //                                                                        established

   led_off_timer = OS_TIMER_CREATE(
         "led_off",  // This name is useful when debugging
         OS_MS_2_TICKS(2000), // Timer duration = 2 seconds
         OS_TIMER_FAIL, // Macro to run if the timer creation fails
         (void *) OS_GET_CURRENT_TASK(), // Task that services the timer ( = this task itself)
         led_off_timer_cb // Callback function to call when the timer expires
   );
   OS_TIMER_START(led_off_timer, OS_TIMER_ONCE); // We only need the timer once per connection
}

Using the SmartBond™ Scanner smartphone app, we can verify that the LED turns on when we connect and is turned back off 2 seconds later.