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

Ble Disconnect from peripheral and Stop Advertising

Hello ,

I'm working on custom board, I'm trying to disconnect from the Central (Andriod app) when the battery is below certain level and stop re-advertising. Below is the piece of code i used:

/* Disconnect and then disable advertising */

if (m_conn_handle != BLE_CONN_HANDLE_INVALID) { sd_ble_gap_disconnect(m_conn_handle,BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION); }

uint32_t err_code = sd_ble_gap_adv_stop();

APP_ERROR_CHECK(err_code);

I'm trying to disconnect and disable advertising but it doesn't work in some cases, I don't really know why.

I use SDK v11 with S132 v2.0.0 (nRF52)

  • meybe after you disconnect, the advertising hasnt started yet. So you call sd_ble_gap_adv_stop() too soon.

  • It will not automatically start to advertise after a disconnection, you are probably calling something like advertising start when you get the BLE_GAP_EVT_DISCONNECTED. So you don't need to call advertising stop, just don't call advertising start.

  • Hey there Vijayalakshmi!

    Take a look into the ble_advertising.c file. There's a piece of code for BLE stack event handling, line #376: void ble_advertising_on_ble_evt(ble_evt_t const * p_ble_evt) { static uint16_t current_slave_link_conn_handle = BLE_CONN_HANDLE_INVALID;

    switch (p_ble_evt->header.evt_id)
    {
        case BLE_GAP_EVT_CONNECTED:
            if (p_ble_evt->evt.gap_evt.params.connected.role == BLE_GAP_ROLE_PERIPH)
            {
                current_slave_link_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
            }
            break;
    
        // Upon disconnection, whitelist will be activated and direct advertising is started.
        case BLE_GAP_EVT_DISCONNECTED:
        {
            uint32_t err_code;
            m_whitelist_temporarily_disabled = false;
    
            if (p_ble_evt->evt.gap_evt.conn_handle == current_slave_link_conn_handle)
            {
               err_code = ble_advertising_start(BLE_ADV_MODE_DIRECTED);
               if ((err_code != NRF_SUCCESS) && (m_error_handler != NULL))
               {
                   m_error_handler(err_code);
               }
            }
            break;
        }
    

    As you can see, on the disconnecting event, advertising gets indeed resumed automatically if you set on your main.c disconnection event handling the communication handle to BLE_CONN_HANDLE_INVALID.

    As a rule of thumb, I noticed that changing the inner workings of the SDK files result in a lot of problems, so I came around this by adding a volatile flag to keep track of when I didn't want advertising to be resumed after disconnection and that worked just fine.

Related