ESP32C3 蓝牙通信程序
时间: 2023-12-17 10:03:34 浏览: 205
esp32进行蓝牙模块的控制与通信 (嵌入式开发 程序 )
5星 · 资源好评率100%
以下是一个 ESP32C3 蓝牙通信程序的示例代码,其中使用了 ESP32C3 IDF 中的蓝牙 API:
```c
#include <stdio.h>
#include "esp_bt.h"
#include "esp_gap_ble_api.h"
#define GATTS_TAG "GATTS_DEMO"
static uint8_t adv_data[30] = {
0x02, 0x01, 0x06, // flags
0x03, 0x03, 0xAA, 0xFE, // 16-bit service UUID
0x0F, 0x09, 'E', 'S', 'P', '3', '2', 'C', '3', ' ', 'B', 'L', 'E', '-', 'T', 'E', 'S', 'T' // complete name
};
static uint8_t test_service_uuid[16] = {
/* LSB <--------------------------------------------------------------------------------> MSB */
// first uuid, 16bit, [12],[13] is the value
0x12,0x34,
// 2nd uuid, 32bit, [12],..,[15] is the value, 0x12345678
0x78,0x56,0x34,0x12,
// 3rd uuid, 128bit, [12],..,[15] is the value, 0x00112233-4455-6677-8899-AABBCCDDEEFF
0x33,0x22,0x11,0x00,0x55,0x44,0x77,0x66,
0x88,0x99,0xAA,0xBB,0xCC,0xDD,0xEE,0xFF,
};
static esp_ble_adv_params_t adv_params = {
.adv_int_min = 0x20,
.adv_int_max = 0x40,
.adv_type = ADV_TYPE_NONCONN_IND,
.own_addr_type = BLE_ADDR_TYPE_PUBLIC,
.channel_map = ADV_CHNL_ALL,
.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY,
};
static void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)
{
switch (event) {
case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT:
esp_ble_gap_start_advertising(&adv_params);
break;
default:
break;
}
}
void app_main()
{
esp_err_t ret;
esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
esp_bt_controller_init(&bt_cfg);
esp_bt_controller_enable(ESP_BT_MODE_BTDM);
esp_bluedroid_init();
esp_bluedroid_enable();
ret = esp_ble_gap_register_callback(gap_event_handler);
if (ret) {
printf("%s gap register failed, error code = %x\n", __func__, ret);
return;
}
ret = esp_ble_gap_set_device_name("ESP32C3 BLE Test");
if (ret) {
printf("%s gap set device name failed, error code = %x\n", __func__, ret);
return;
}
ret = esp_ble_gap_config_adv_data_raw(adv_data, sizeof(adv_data));
if (ret) {
printf("%s gap config adv data failed, error code = %x\n", __func__, ret);
return;
}
esp_ble_uuid_t service_uuid;
esp_bt_uuid_t uuid_obj;
uuid_obj.len = ESP_UUID_LEN_128;
memcpy(uuid_obj.uuid.uuid128, test_service_uuid, ESP_UUID_LEN_128);
esp_ble_uuid_convert(&uuid_obj, &service_uuid);
ret = esp_ble_gatts_create_service(&service_uuid, ESP_GATT_SVC_TYPE_PRIMARY, 0x40, &gatts_if);
if (ret) {
printf("%s gatts create service failed, error code = %x\n", __func__, ret);
return;
}
ret = esp_ble_gatts_start_service(gatts_if);
if (ret) {
printf("%s gatts start service failed, error code = %x\n", __func__, ret);
return;
}
printf("ESP32C3 BLE Test started\n");
}
```
这个示例程序实现了一个简单的 BLE 广播和 GATT 服务,其中包括:
- 设置广播数据和参数
- 注册 GAP 事件回调函数
- 注册 GATT 服务和特征
- 启动 BLE 广播和 GATT 服务
通过修改代码,你可以自定义自己的 BLE 广播和 GATT 服务。
阅读全文