使用Arduino开发ESP32(十九):BLE_write,用BLE收发信息

这也是BLE应用的最后一篇了
所用到的函数在前文也有所提及,代码也很简单
故,今天直入主题

代码:

/*
    Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleWrite.cpp
    Ported to Arduino ESP32 by Evandro Copercini
*/

#include 
#include 
#include 

// See the following for generating UUIDs:
// https://www.uuidgenerator.net/

#define SERVICE_UUID        "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"


class MyCallbacks: public BLECharacteristicCallbacks {
  
    void onWrite(BLECharacteristic *pCharacteristic) {      //写方法
      
      std::string value = pCharacteristic->getValue();      //接收值
      if (value.length() > 0) {
        Serial.println("*********");
        Serial.print("收到新信息: ");
        for (int i = 0; i < value.length(); i++)       //遍历输出字符串
          Serial.print(value[i]);

        Serial.println();
        Serial.println("*********");
      }
    }
};

void setup() {
  Serial.begin(115200);

  Serial.println("1- 在你的手机上下载安装一个BLE scanner app");
  Serial.println("2- 在app上扫描蓝牙设备");
  Serial.println("3- 连接至MyESP32");
  Serial.println("4- 点击CUSTOM SERVICE栏的CUSTOM CHARACTERISTIC,写一些数据");
  Serial.println("5- 查看结果:D");

  BLEDevice::init("MyESP32");                      //设备初始化,名称MyESP32
  
  BLEServer *pServer = BLEDevice::createServer();            //BLEServer指针,创建Server

  BLEService *pService = pServer->createService(SERVICE_UUID);     //BLEService指针,创建Service

  BLECharacteristic *pCharacteristic = pService->createCharacteristic(     //BLECharacteristic指针,创建Characteristic
                                         CHARACTERISTIC_UUID,
                                         BLECharacteristic::PROPERTY_READ |
                                         BLECharacteristic::PROPERTY_WRITE
                                       );

  pCharacteristic->setCallbacks(new MyCallbacks());            //设置回调函数

  pCharacteristic->setValue("Hello World");    //发送信息,hello world
  pService->start();                      //开启服务

  BLEAdvertising *pAdvertising = pServer->getAdvertising();        //初始化广播
  pAdvertising->start();                    //开始广播
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(2000);
}

结果

在app上查看esp32发出的信息
使用Arduino开发ESP32(十九):BLE_write,用BLE收发信息_第1张图片
复制ASCII码,将其发送回去
使用Arduino开发ESP32(十九):BLE_write,用BLE收发信息_第2张图片
查看消息
使用Arduino开发ESP32(十九):BLE_write,用BLE收发信息_第3张图片

你可能感兴趣的:(ESP32学习之路)