使用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 <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>

// 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发出的信息
在这里插入图片描述
复制ASCII码,将其发送回去
在这里插入图片描述
查看消息
在这里插入图片描述

  • 3
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值