ESP32单片机基础入门

第6课:蓝牙双模技术(BLE+经典蓝牙)

BLE广播与GATT服务

BLE基础概念

蓝牙低功耗(BLE)是ESP32支持的重要无线通信协议,具有低功耗、快速连接的特点。

BLE设备通过广播数据包被发现,广播数据包含设备名称、服务UUID等信息。

BLE广播配置

ESP32设置BLE广播的基本步骤:

                #include <BLEDevice.h>
                #include <BLEUtils.h>
                #include <BLEServer.h>
                
                void setup() {
                    BLEDevice::init("ESP32_BLE_Device");
                    BLEServer *pServer = BLEDevice::createServer();
                    
                    // 创建广播对象
                    BLEAdvertising *pAdvertising = pServer->getAdvertising();
                    pAdvertising->addServiceUUID(SERVICE_UUID);
                    pAdvertising->setScanResponse(true);
                    pAdvertising->setMinPreferred(0x06);  // 有助于iPhone连接
                    pAdvertising->setMinPreferred(0x12);
                    
                    // 开始广播
                    pAdvertising->start();
                }
            

GATT服务与特征值

GATT(Generic Attribute Profile)定义了BLE设备间数据传输的方式:

                // 创建服务
                BLEService *pService = pServer->createService(SERVICE_UUID);
                
                // 创建特征值
                BLECharacteristic *pCharacteristic = pService->createCharacteristic(
                    CHARACTERISTIC_UUID,
                    BLECharacteristic::PROPERTY_READ | 
                    BLECharacteristic::PROPERTY_WRITE |
                    BLECharacteristic::PROPERTY_NOTIFY
                );
                
                // 添加描述符
                pCharacteristic->addDescriptor(new BLE2902());
                
                // 启动服务
                pService->start();
            

SPP串口透传(经典蓝牙)

经典蓝牙概述

ESP32支持经典蓝牙(Bluetooth Classic),可实现SPP(Serial Port Profile)串口透传功能。

注意:经典蓝牙相比BLE功耗更高,适合需要较高数据传输速率的应用。

SPP串口配置

ESP32设置SPP串口透传的基本步骤:

                #include "BluetoothSerial.h"
                
                BluetoothSerial SerialBT;
                
                void setup() {
                    Serial.begin(115200);
                    SerialBT.begin("ESP32_SPP"); // 蓝牙设备名称
                    Serial.println("蓝牙设备已启动,等待连接...");
                }
                
                void loop() {
                    if (Serial.available()) {
                        SerialBT.write(Serial.read());
                    }
                    if (SerialBT.available()) {
                        Serial.write(SerialBT.read());
                    }
                    delay(20);
                }
            

配对与连接

SPP连接过程:

  1. 设备进入可发现模式
  2. 客户端设备搜索并选择ESP32
  3. 完成配对(如果需要PIN码)
  4. 建立SPP连接

数据传输优化

为提高SPP传输效率,可采取以下措施:

                // 设置PIN码增加安全性
                SerialBT.setPin("1234");
                
                // 检查连接状态
                if(SerialBT.connected()) {
                    // 发送数据
                    SerialBT.println("Hello from ESP32!");
                }
            
客服小姐姐(优先添加)

客服小姐姐(优先添加)

客服微信

讲师微信(备用)