蓝牙发送通知

零知ESP32具有低功耗蓝牙(BLE)功能,它是蓝牙的一种节能形式。 BLE的主要应用是短距离传输少量数据,它的目标是在使用纽扣电池的超低功耗应用中。

在此实例中,我们将设置ESP32为发送通知消息的服务器,当蓝牙客户端连接时, 每两秒发送一次消息。

一、软件和硬件

硬件我们本次使用零知-ESP32

软件:零知开发工具和 手机APP:nRF Connect


二、方法步骤

将零知ESP32开发板连接到USB,打开零知开发工具,新建项目,复制下面的代码。


							
	#include <BLEDevice.h>
	#include <BLEServer.h>
	#include <BLEUtils.h>
	#include <BLE2902.h>
	 
	BLECharacteristic *pCharacteristic;
	bool deviceConnected = false;
	uint8_t value = 0;
	 
	#define SERVICE_UUID        "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
	#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
	 
	 
	class MyServerCallbacks: public BLEServerCallbacks {
	    void onConnect(BLEServer* pServer) {
	      deviceConnected = true;
	    };
	 
	    void onDisconnect(BLEServer* pServer) {
	      deviceConnected = false;
	    }
	};
	 
	 
	 
	void setup() {
	  Serial.begin(9600);
	 
	  // Create the BLE Device
	  BLEDevice::init("MyESP32");
	 
	  // Create the BLE Server
	  BLEServer *pServer = BLEDevice::createServer();
	  pServer->setCallbacks(new MyServerCallbacks());
	 
	  // Create the BLE Service
	  BLEService *pService = pServer->createService(SERVICE_UUID);
	 
	  // Create a BLE Characteristic
	  pCharacteristic = pService->createCharacteristic(
	                      CHARACTERISTIC_UUID,
	                      BLECharacteristic::PROPERTY_READ   |
	                      BLECharacteristic::PROPERTY_WRITE  |
	                      BLECharacteristic::PROPERTY_NOTIFY |
	                      BLECharacteristic::PROPERTY_INDICATE
	                    );
	 
	  // Create a BLE Descriptor
	  pCharacteristic->addDescriptor(new BLE2902());
	 
	  // Start the service
	  pService->start();
	 
	  // Start advertising
	  pServer->getAdvertising()->start();
	  Serial.println("Waiting a client connection to notify...");
	}
	 
	void loop() {
	 
	  if (deviceConnected) {
	    Serial.printf("*** NOTIFY: %d ***\n", value);
	    pCharacteristic->setValue(&value, 1);
	    pCharacteristic->notify();
	    //pCharacteristic->indicate();
	    value++;
	  }
	  delay(2000);
	}
							
						

导入程序代码,在右侧选择ESP32开发板,然后验证程序,如图:

然后上传程序到开发板,打开串口调试窗口,此时ESP32已开启蓝牙通知功能,等待连接。 打开手机APP:nRF Connect,搜索蓝牙设备,如图:

连接“MyESP32”,就可以接收到消息通知了。

下图是调试窗口打印的发送信息: