ESP32-C2 蓝牙应用指南及代码示例
一、蓝牙扫描流程
-
初始化蓝牙扫描参数:
esp_ble_scan_params_t scan_params = { .scan_type = BLE_SCAN_TYPE_PASSIVE, .own_addr_type = BLE_ADDR_TYPE_PUBLIC, .scan_filter_policy = BLE_SCAN_FILTER_ALLOW_ALL, .scan_interval = 0x50, .scan_window = 0x30 }; esp_ble_gap_set_scan_params(&scan_params);
-
启动扫描:
esp_ble_gap_start_scanning(duration); // 设置扫描时长(秒)
-
处理扫描结果:
void esp_gap_cb(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) { if (event == ESP_GAP_BLE_SCAN_RESULT_EVT) { esp_ble_gap_cb_param_t::scan_rst scan_rst = param->scan_rst; ESP_LOGI(TAG, "Device found: %s", scan_rst.bda); // 扫描结果处理逻辑 } }
二、设备连接与特征读取
-
设备连接:
esp_ble_gattc_open(gattc_if, remote_device_addr, BLE_ADDR_TYPE_PUBLIC, true);
-
设置MTU:
esp_ble_gattc_send_mtu_req(gattc_if, conn_id);
-
发现服务:
esp_ble_gattc_search_service(gattc_if, conn_id, NULL);
-
获取特征:
esp_ble_gattc_get_char_by_uuid(gattc_if, conn_id, service_start_handle, service_end_handle, &char_uuid, char_elem_result, &count);
三、注册通知与数据交互
-
注册通知:
esp_ble_gattc_register_for_notify(gattc_if, remote_bda, char_handle);
-
处理通知:
if (event == ESP_GATTC_NOTIFY_EVT) { ESP_LOGI(TAG, "Notification received: %s", param->notify.value); }
-
发送数据:
uint8_t data[20] = {0x01, 0x02, 0x03}; esp_ble_gattc_write_char(gattc_if, conn_id, char_handle, sizeof(data), data, ESP_GATT_WRITE_TYPE_RSP, ESP_GATT_AUTH_REQ_NONE);
四、优化与低功耗设计
-
使用低功耗模式:
esp_ble_gap_set_scan_params(&scan_params); // 设置较长的扫描间隔,减少功耗
-
避免不必要的重连和数据传输,以节省能量。
结论
通过本文的代码示例,开发者可以在ESP32-C2上快速实现蓝牙扫描、连接与数据交互的基本功能。结合蓝牙低功耗设计,ESP32-C2非常适合应用于各种IoT场景中。