esp32c2 扫描 esp32 蓝牙扫描

ESP32-C2 蓝牙应用指南及代码示例

一、蓝牙扫描流程
  1. 初始化蓝牙扫描参数

    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);
    
  2. 启动扫描

    esp_ble_gap_start_scanning(duration);  // 设置扫描时长(秒)
    
  3. 处理扫描结果

    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);
            // 扫描结果处理逻辑
        }
    }
    
二、设备连接与特征读取
  1. 设备连接

    esp_ble_gattc_open(gattc_if, remote_device_addr, BLE_ADDR_TYPE_PUBLIC, true);
    
  2. 设置MTU

    esp_ble_gattc_send_mtu_req(gattc_if, conn_id);
    
  3. 发现服务

    esp_ble_gattc_search_service(gattc_if, conn_id, NULL);
    
  4. 获取特征

    esp_ble_gattc_get_char_by_uuid(gattc_if, conn_id, service_start_handle, service_end_handle, &char_uuid, char_elem_result, &count);
    
三、注册通知与数据交互
  1. 注册通知

    esp_ble_gattc_register_for_notify(gattc_if, remote_bda, char_handle);
    
  2. 处理通知

    if (event == ESP_GATTC_NOTIFY_EVT) {
        ESP_LOGI(TAG, "Notification received: %s", param->notify.value);
    }
    
  3. 发送数据

    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);
    
四、优化与低功耗设计
  1. 使用低功耗模式:

    esp_ble_gap_set_scan_params(&scan_params); // 设置较长的扫描间隔,减少功耗
    
  2. 避免不必要的重连和数据传输,以节省能量。

结论

通过本文的代码示例,开发者可以在ESP32-C2上快速实现蓝牙扫描、连接与数据交互的基本功能。结合蓝牙低功耗设计,ESP32-C2非常适合应用于各种IoT场景中。

在这里插入图片描述
ESP32-C2模组

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值