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

How can I make an automatic Bluetooth connection?

Hello,

I have a question about Bluetooth connectivity issues.  The BLE code I'm trying to make will be connected to the smartphone (Android).  If phone out of the Bluetooth range and return to the reachable range when the connection is lost, I want Bluetooth to automatically reconnect.

How do I implement this?

Thank you.

Parents
  • Hi,

    Advertising is typically is configured by calling ble_advertising_init() and started by calling ble_advertising_start(). When calling ble_advertising_init() you can configure it to advertise on disconnect by:

    init.config.ble_adv_on_disconnect_disabled     = false;

    Best regards,
    Kenneth

  • Hello Kenneth!

    As you said, I can enable or disable automatic pairing by adding that code.

    But it only works when I manually disconnect it.  The function I want is similar to Bluetooth earphones.  The Bluetooth connection may be lost, such as when the Central is out of range of Bluetooth communication or when power is off. And if it's possible to reconnect, It is sending a pairing request to the Central that previously connected to.

    Can you help me with this?

    Thank you.

    static void advertising_init(void)
    {
        uint32_t               err_code;
        ble_advertising_init_t init;
    
        memset(&init, 0, sizeof(init));
    
        init.advdata.name_type          = BLE_ADVDATA_FULL_NAME;
        init.advdata.include_appearance = false; 
        init.advdata.flags              = BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE; 
    
        init.srdata.uuids_complete.uuid_cnt = sizeof(m_adv_uuids) / sizeof(m_adv_uuids[0]);
        init.srdata.uuids_complete.p_uuids  = m_adv_uuids;
    
        init.config.ble_adv_fast_enabled  = true;
        init.config.ble_adv_fast_interval = APP_ADV_INTERVAL;
        init.config.ble_adv_fast_timeout  = APP_ADV_DURATION; //advertising timeout
        init.evt_handler = on_adv_evt;
    
        init.config.ble_adv_on_disconnect_disabled = false; //Auto pairing test, true : if disconnet no advertising(scan) / false : if disconnet auto advertising(scan) and connected
    
        err_code = ble_advertising_init(&m_advertising, &init);
        APP_ERROR_CHECK(err_code);
    
        ble_advertising_conn_cfg_tag_set(&m_advertising, APP_BLE_CONN_CFG_TAG);
    }
    

  • The application may call ble_advertising_start() at any time, for instance on the BLE_GAP_EVT_CONNECTED event.

    Best regards,
    Kenneth

Reply Children
No Data
Related