远程点亮ESP32开发板 蓝牙控制

ESP32的另外一个基本功能就是它的蓝牙功能,现在我们就基于该功能实现远程控制零知ESP32板载LED灯的打开和关闭操作。

一、软件和硬件

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

二、方法步骤


							
	#include <BLEDevice.h>
	#include <BLEUtils.h>
	#include <BLEServer.h>
	  
	// See the following for generating UUIDs:
	// [url=https://www.uuidgenerator.net/]https://www.uuidgenerator.net/[/url]
	  
	#define SERVICE_UUID        "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
	#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
	  
	#define LED 2
	  
	class MyCallbacks: public BLECharacteristicCallbacks {
	    void onWrite(BLECharacteristic *pCharacteristic) {
	      std::string value = pCharacteristic->getValue();
	  
	      if (value.length() > 0) {
	        Serial.println("*********");
	        Serial.print("New value: ");
	        for (int i = 0; i < value.length(); i++)
	          Serial.print(value[i]);
	          
	        if(value == "开灯"){
	            digitalWrite(LED,HIGH);
	        }else if(value == "关灯"){
	            digitalWrite(LED,LOW);
	        }
	  
	        Serial.println();
	        Serial.println("*********");
	      }
	    }
	};
	  
	void setup() {
	  Serial.begin(115200);
	  
	//  Serial.println("1- Download and install an BLE scanner app in your phone");
	//  Serial.println("2- Scan for BLE devices in the app");
	//  Serial.println("3- Connect to MyESP32");
	//  Serial.println("4- Go to CUSTOM CHARACTERISTIC in CUSTOM SERVICE and write something");
	//  Serial.println("5- See the magic =)");
	      
	    pinMode(LED,OUTPUT);
	  
	  BLEDevice::init("MyESP32");
	  BLEServer *pServer = BLEDevice::createServer();
	  
	  BLEService *pService = pServer->createService(SERVICE_UUID);
	  
	  BLECharacteristic *pCharacteristic = pService->createCharacteristic(
	                                         CHARACTERISTIC_UUID,
	                                         BLECharacteristic::PROPERTY_READ |
	                                         BLECharacteristic::PROPERTY_WRITE
	                                       );
	  
	  pCharacteristic->setCallbacks(new MyCallbacks());
	  
	  pCharacteristic->setValue("Hello World");
	  pService->start();
	  
	  BLEAdvertising *pAdvertising = pServer->getAdvertising();
	  pAdvertising->start();
	}
	  
	void loop() {
	  // put your main code here, to run repeatedly:
	  delay(2000);
	}
							
						

1)打开串口调试窗口,可以看到如下信息:

(2)我们现在用手机APP控制LED,先需要下载一个蓝牙调试工具,或者自己写一个蓝牙控制APP,这里用BLE Utility工具为例:

ble_utility_v2.5.apk.7z(点击下载)

安装这个工具后,打开并连接我们的ESP32:

连接成功后,我们可以对下面这个服务进行读写操作了:

点击读取,就可以从ESP32获取到如下信息:

我们现在给ESP32 发送一个“开灯”命令,然后,可以看到ESP32板的LED灯亮了:

然后发送“关灯”操作,可以关闭板子的LED灯,可以看到数据传输的log:

同时在零知开发工具的串口调试窗口,可以看到如下交互信息: