目录
1.引入连接头文件
#include <zephyr/bluetooth/conn.h>
2. 连接和断开的回调函数
- 连接回调函数的指针存放在bt_conn_cb类型变量里面,因此需要创建变量
定义连接和断开的回调函数
void on_connected(struct bt_conn *conn, uint8_t err)
{
if (err)
{
LOG_ERR("Connection error %d", err);
return;
}
LOG_INF("Connected");
my_conn = bt_conn_ref(conn);
dk_set_led(CONNECTION_STATUS_LED, 1);
}
void on_disconnected(struct bt_conn *conn, uint8_t reason)
{
LOG_INF("Disconnected,Reason %d", reason);
bt_conn_unref(my_conn);
dk_set_led(CONNECTION_STATUS_LED, 0);
}
将回调函数放入bt_conn_cb 类型变量,待会注册回调函数需要用到。
struct bt_conn_cb connection_callbacks = {
.connected = on_connected,
.disconnected = on_disconnected,
};
注册回调函数
bt_conn_cb_register(&connection_callbacks);
编译和运行
更新连接参数实例
- 创建一个存储连接参数的变量,并获取当前参数,注意这一步是在连接成功的回调函数里面操作。
struct bt_conn_info info;
err = bt_conn_get_info(conn, &info);
if (err) {
LOG_ERR("bt_conn_get_info() returned %d", err);
return;
}
2.增加回调函数,这样在有参数更新的时候,就可以有回调产生
struct bt_conn_cb connection_callbacks = {
.connected = on_connected,
.disconnected = on_disconnected,
/* STEP 4.1 - Add the callback for connection parameter updates */
.le_param_updated = on_le_param_updated,
/* STEP 8.3 - Add the callback for PHY mode updates */
.le_phy_updated = on_le_phy_updated,
/* STEP 13.2 - Add the callback for data length updates */
.le_data_len_updated = on_le_data_len_updated,
};
3.配置自己的连接参数,使用prj.conf文件配置
CONFIG_BT_PERIPHERAL_PREF_MIN_INT=800
CONFIG_BT_PERIPHERAL_PREF_MAX_INT=800
CONFIG_BT_PERIPHERAL_PREF_LATENCY=0
CONFIG_BT_PERIPHERAL_PREF_TIMEOUT=400
CONFIG_BT_GAP_AUTO_UPDATE_CONN_PARAMS=y