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

I'd like to know how to check the Bluetooth pairing connection in loop().

Hello


I use the SDK v17 and the example ble_app_uart and use various functions such as LED, timer, buzzer, etc.
I want these functions to work after Bluetooth is connected.

To do this, I need to be able to see when Bluetooth is connected and when it is disconnected.

static void ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context)
{
    uint32_t err_code;

    switch (p_ble_evt->header.evt_id)
    {
        case BLE_GAP_EVT_CONNECTED:
            NRF_LOG_INFO("Connected");
            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
            APP_ERROR_CHECK(err_code);
            m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
            err_code = nrf_ble_qwr_conn_handle_assign(&m_qwr, m_conn_handle);
            APP_ERROR_CHECK(err_code);
            break;
            
          case BLE_GAP_EVT_DISCONNECTED:
            NRF_LOG_INFO("Disconnected");
            // LED indication will be changed when advertising starts.
            m_conn_handle = BLE_CONN_HANDLE_INVALID;
            break;
    }
}

If I look at the ble_evt_handler code in the example ble_uart, there is a code for when Bluetooth is connected and when it is disconnected. 

How can I use this?

Thank you always for your help!

  • Hello,

    To do this, I need to be able to see when Bluetooth is connected and when it is disconnected.

    If I look at the ble_evt_handler code in the example ble_uart, there is a code for when Bluetooth is connected and when it is disconnected. 

    How can I use this?

    I assume you are referring to the m_conn_handle variable here?
    The simplest way to use this variable would be to create conditional checks in your program that checks whether the connection handle is INVALID or not. You may then proceed with using the peripherals.
    However, what I would recommend you do is to create a function to start and stop all your peripherals, and call it from the CONNECTED event.
    So, for example, you would like a button and LED to be functional only when connected. Then you may create a button_and_led_start function, which you call from the CONNECTED event.
    Then you will also need to create and call a button_and_let_stop function, to be called in the DISCONNECTED event.

    This way, your peripherals may be in a low-power or completely OFF when the device is not in a connection, which will drastically reduce average power consumption if your device is not always in a connection.

    Best regards,
    Karl

Related