两个手机的蓝牙app作为主机蓝牙连接一个nrf52832蓝牙模块,当第一台手机连接上nrf52832从机模块,其他手机就无法搜索到nrf52832从机模块的蓝牙名称了,这个nrf52832从机模块的实现代码怎么写呢?
时间: 2023-08-24 14:04:00 浏览: 333
nrf52832从机模块的实现代码需要使用SoftDevice API来实现蓝牙连接和广播。以下是一个简单的示例代码,用于设置从机模块的蓝牙名称和广播参数:
```c
#include "nrf_sdh.h"
#include "nrf_sdh_ble.h"
#include "nrf_ble_qwr.h"
#include "nrf_ble_gatt.h"
#include "nrf_ble_scan.h"
#include "nrf_ble_advertising.h"
#define DEVICE_NAME "MyDevice" // 设置从机模块的蓝牙名称
static ble_gap_adv_params_t m_adv_params; // 广播参数
void ble_stack_init(void)
{
ret_code_t ret;
// Initialize the SoftDevice handler module.
NRF_SDH_BLE_OBSERVER(m_ble_observer, APP_BLE_OBSERVER_PRIO, ble_evt_handler, NULL);
ret = nrf_sdh_enable_request();
APP_ERROR_CHECK(ret);
// Wait for SoftDevice to be enabled
while (nrf_sdh_is_enabled() == false)
{
// Do nothing.
}
// Enable BLE stack.
ret = nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, &cfg_ble);
APP_ERROR_CHECK(ret);
ret = nrf_sdh_ble_enable(&ram_start);
APP_ERROR_CHECK(ret);
}
void advertising_init(void)
{
ret_code_t ret;
uint8_t flags = BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED;
memset(&m_adv_params, 0, sizeof(m_adv_params));
m_adv_params.properties.type = BLE_GAP_ADV_TYPE_CONNECTABLE_SCANNABLE_UNDIRECTED;
m_adv_params.p_peer_addr = NULL;
m_adv_params.filter_policy = BLE_GAP_ADV_FP_ANY;
m_adv_params.interval = MSEC_TO_UNITS(100, UNIT_0_625_MS);
m_adv_params.duration = BLE_GAP_ADV_TIMEOUT_GENERAL_UNLIMITED;
m_adv_params.primary_phy = BLE_GAP_PHY_1MBPS;
m_adv_params.secondary_phy = BLE_GAP_PHY_1MBPS;
m_adv_params.scan_req_notification = false;
m_adv_params.discovery_mode = BLE_GAP_DISCOVERY_MODE_GENERAL;
// Add advertising data.
ble_advdata_t advdata;
memset(&advdata, 0, sizeof(advdata));
advdata.name_type = BLE_ADVDATA_FULL_NAME;
advdata.include_appearance = false;
advdata.flags = flags;
advdata.uuids_complete.uuid_cnt = 0;
advdata.uuids_complete.p_uuids = NULL;
// Set device name and advertising data.
ble_advdata_manuf_data_t manuf_data;
memset(&manuf_data, 0, sizeof(manuf_data));
manuf_data.company_identifier = 0x0059; // 设置厂商标识
manuf_data.data.p_data = NULL;
manuf_data.data.size = 0;
advdata.p_manuf_specific_data = &manuf_data;
ret = ble_advdata_encode(&advdata, m_adv_params.adv_data.p_data, &m_adv_params.adv_data.len);
APP_ERROR_CHECK(ret);
}
void advertising_start(void)
{
ret_code_t ret;
// Start advertising.
ret = sd_ble_gap_adv_start(&m_adv_params, APP_BLE_CONN_CFG_TAG);
APP_ERROR_CHECK(ret);
}
```
在这个示例代码中,首先需要初始化蓝牙协议栈,然后进行广播参数的设置和广播的开启。在设置广播参数时,需要指定广播类型、广播间隔、厂商标识等信息。在设置完广播参数之后,可以使用`sd_ble_gap_adv_start`函数开启广播。
需要注意的是,在蓝牙连接时,从机模块需要通过`sd_ble_gap_connect`函数响应主机的连接请求。如果从机模块已经与一个主机建立了连接,其他主机将无法连接该从机模块。如果需要支持多主机连接,需要使用多连接的蓝牙模块或者手动管理连接。
阅读全文