ESP32-S3(N4) IoT 开发板是一款基于乐鑫ESP32-S3-WROOM-1-N4模组设计的开发,它支持WIFI和蓝牙5.0双模通讯。 file:///C:/Users/LilyL/AppData/Local/Temp/ksohtml12488/wps1.png因此,它要与手机进行通讯是十分方便的。 蓝牙连接与断开处理的函数为: - class MyServerCallbacks: public BLEServerCallbacks {
- void onConnect(BLEServer* pServer) { //当蓝牙连接时会执行该函数
- Serial.println("蓝牙已连接");
- deviceConnected = true;
- };
- void onDisconnect(BLEServer* pServer) { //当蓝牙断开连接时会执行该函数
- Serial.println("蓝牙已断开");
- deviceConnected = false;
- delay(500); // give the bluetooth stack the chance to get things ready
- pServer->startAdvertising(); // restart advertising
- }
- };
蓝牙接收数据的函数为: - class MyCallbacks: public BLECharacteristicCallbacks {
- void onWrite(BLECharacteristic *pCharacteristic) {
- String rxValue = pCharacteristic->getValue();//接收数据,并赋给rxValue
- if (rxValue.length() > 0) {
- Serial.println("*********");
- Serial.print("Received Value: ");
- for (int i = 0; i < rxValue.length(); i++){
- Serial.print(rxValue[i]);
- }
- Serial.println();
- Serial.println("*********");
- }
- }
- };
蓝牙初始化的函数为: - void BLEBegin(){
- BLEDevice::init(/*BLE名称*/"UART Service");
- pServer = BLEDevice::createServer();
- pServer->setCallbacks(new MyServerCallbacks());
- BLEService *pService = pServer->createService(SERVICE_UUID);
- pTxCharacteristic = pService->createCharacteristic(
- CHARACTERISTIC_UUID_TX,
- BLECharacteristic::PROPERTY_NOTIFY
- );
- pTxCharacteristic->addDescriptor(new BLE2902());
- BLECharacteristic * pRxCharacteristic = pService->createCharacteristic(
- CHARACTERISTIC_UUID_RX,
- BLECharacteristic::PROPERTY_WRITE
- );
- pRxCharacteristic->setCallbacks(new MyCallbacks());
- pService->start();
- pServer->getAdvertising()->start();
- Serial.println("Waiting a client connection to notify...");
- }
实现手机发送数据的主要程序为: - void setup() {
- Serial.begin(115200);
- BLEBegin(); //初始化蓝牙
- }
- void loop() {
- if (deviceConnected) { //如果有蓝牙连接,就发送数据
- pTxCharacteristic->setValue("Hello"); //发送字符串
- pTxCharacteristic->notify();
- delay(10); // bluetooth stack will go into congestion, if too many packets are sent
- pTxCharacteristic->setValue("DFRobot"); //发送字符串
- pTxCharacteristic->notify();
- delay(10); // bluetooth stack will go into congestion, if too many packets are sent
- }
- }
经程序上传,通过手机上的小程序BLE调试助手,即可向外发送数据,其测试结果如图1至图3所示。 图1 串口接收手机发送内容
图2 串口监视器接收效果
图3 手机退出连接
|