Arduino ESP32 BLE


一. 藍牙基礎知識

1. 藍牙4.0和BLE的區分

通常在了解一點藍牙的朋友看來,往往將BLE等同於藍牙4.0,其實不然。

藍牙4.0是協議,4.0是協議版本號,藍牙4.0是2010年6月由SIG(Special Interest Group)發布的藍牙標准,它有2種模式:

BLE(Bluetooth low energy)只能與4.0協議設備通信,適應節能且僅收發少量數據的設備(如家用電子);

BR/EDR(Basic Rate / Enhanced Data Rate),向下兼容(能與3.0/2.1/2.0通信),適應收發數據較多的設備(如耳機)。這個模式常常也有人稱之為“傳統藍牙”或“經典藍牙”。

可以這樣理解,藍牙4.0協議包含BLE,BLE隸屬於藍牙4.0協議的一部分

2. BLE和雙模藍牙的概念

Bluetooth Low Energy (也被稱為Bluetooth 4.0、BLE、BTLE),下面記作BLE,是使用2.4GHz的無線短距離無線通信標准。 迄今為止,雖然高速藍牙已經實現,但BLE在通訊速度上比較普通,主要強調一個紐扣電池能夠工作幾年的這種省電性能。

設備端和主機端使用GATT(Generic ATTribute) profile進行通信。 如果你聽到GATT這個名詞,就可以將其想成使用BLE,這沒什么問題。

由於與傳統藍牙不兼容,在主機端,和藍牙3.0合並做為雙模,實現成兩者都可以使用的情況比較多。

3. BLE藍牙架構圖(了解)

 
 

最上面綠色的部分是應用層,主要是gatt和att我們可以把它看作是同一層。
sm是安全管理層,負責管理安全。
最下面link layer層和phy層基本上就是一些rf的處理。

4. GATT概念

GATT已經成為BLE通信的規定,每一個設備中存在很多的“service”(服務),service中還包含有多個“Characteristic”(特征值)。
在藍牙實際數據交換中,就是通過讀寫這些“Characteristic”來實現的。

 
 
  • 一個鼠標是一個BLEDevice
  • 一個BLEDevice建立了一個BLE服務器 BLEServer
  • 一個BLE服務器里有多個服務BLEService
  • 一個服務里有多個特征值BLECharacteristic 每個特征值是一種數據.就是通過讀寫這些“Characteristic”實現讀寫數據

每個characteristic的值可以在不加密的狀態下讀寫,但配對的操作是加密的。 還有當characteristic的值已改變時,可接收通知(notify)。關於通知的概念請見下面小節.

5. UUID

服務和characteristic是通過UUID來進行識別的。

UUID是32位的,但那些被藍牙技術聯盟的標准中定義的UUID是以四個數字來表示的。UUID既有16位的也有128位的,我們需要了解的是16位的UUID是經過藍牙組織認證的,是需要購買的,當然也有一些通用的16位UUID。

UUID:由藍牙設備廠商提供的UUID,UUID是在硬件編程里已經確定了的,想要操作特定的服務、特征值都需要通過UUID來找。

6. notify通知的概念

如果主機的一個特征值characteristic發生改變, 可以使用通知notify來告訴客戶端. 這是服務器主動給客戶端發的信息, 並非是響應客戶端的請求.

這樣做有很多好處, 比如ESP32采集到了溫度的變化, 可以將數據寫入對應的特征值characteristic,然后notify通知客戶端.

我們創建特征值時, 把它規定為通知類型, 當這個特征值發生變化時,可以通知客戶端,像這樣:

pCharacteristic = pService->createCharacteristic(CHARACTERISTIC_UUID_TX, BLECharacteristic::PROPERTY_NOTIFY); 
//創建一個(讀)特征值, 它是通知下發類型的特征值

其實客戶端可以不接受服務器發送的notify,方法是修改自己的Descriptor. BLE服務器看到你對自己的描述中標識了不想接收notify,也就不會再給你發了.詳見下面的視頻.

7. write寫入的概念

我們可以把特征值定為寫入類型, 這樣客戶端可以給我們寫入, 觸發寫入回調函數

BLECharacteristic *pCharacteristic = pService->createCharacteristic(CHARACTERISTIC_UUID_RX, BLECharacteristic::PROPERTY_WRITE);
//創建一個(寫)特征, 它是寫入類型的特征值
  pCharacteristic->setCallbacks(new MyCallbacks());  
//為特征添加一個回調

除了通知和寫入, 還有好幾種特征值類型, 請后續了解

 

 其實BLE理論非常復雜,但我們理解到這個程度即可.附上一個幫助我們理解的視頻:
https://www.bilibili.com/video/bv17v41117sq

二. ESP32 arduino 藍牙BLE通訊的實現

1. 思路

把藍牙設備看作服務器, 把手機看作一個客戶端, 客戶端可以給服務器發送數據, 服務器可以給客戶端下發通知

實現思路:

  1. 創建BLE設備 BLEDevice::init(ble_name);
  2. 創建BLE服務器 BLEServer *pServer = BLEDevice::createServer();
  3. 創建若干服務 BLEService *pService = pServer->createService(SERVICE_UUID);
  4. 創建服務的特征值

下面的例子中, 我們創建了一個叫做pService 的服務, 這個服務其實是為了模擬串口
為了實現"串口",我們在這個服務下添加了兩個特征值, 一個是TX. 一個是RX.

#include <Arduino.h>
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
#include <String.h>

BLECharacteristic *pCharacteristic; //創建一個BLE特性pCharacteristic
bool deviceConnected = false;       //連接否標志位
uint8_t txValue = 0;                //TX的值
long lastMsg = 0;                   //存放時間的變量
String rxload = "BlackWalnutLabs";  //RX的預置值

#define SERVICE_UUID "6E400001-B5A3-F393-E0A9-E50E24DCCA9E" // UART service UUID
#define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
#define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"

//服務器回調
class MyServerCallbacks : public BLEServerCallbacks
{
  void onConnect(BLEServer *pServer)
  {
    deviceConnected = true;
  };
  void onDisconnect(BLEServer *pServer)
  {
    deviceConnected = false;
  }
};

//特性回調
class MyCallbacks : public BLECharacteristicCallbacks
{
  void onWrite(BLECharacteristic *pCharacteristic)
  {
    std::string rxValue = pCharacteristic->getValue();
    if (rxValue.length() > 0)
    {
      rxload = "";
      for (int i = 0; i < rxValue.length(); i++)
      {
        rxload += (char)rxValue[i];
        Serial.print(rxValue[i]);
      }
      Serial.println("");
    }
  }
};

void setupBLE(String BLEName)
{
  const char *ble_name = BLEName.c_str(); //將傳入的BLE的名字轉換為指針
  BLEDevice::init(ble_name);              //初始化一個藍牙設備

  BLEServer *pServer = BLEDevice::createServer(); // 創建一個藍牙服務器
  pServer->setCallbacks(new MyServerCallbacks()); //服務器回調函數設置為MyServerCallbacks

  BLEService *pService = pServer->createService(SERVICE_UUID); //創建一個BLE服務

  pCharacteristic = pService->createCharacteristic(CHARACTERISTIC_UUID_TX, BLECharacteristic::PROPERTY_NOTIFY); 
//創建一個(讀)特征值 類型是通知
  pCharacteristic->addDescriptor(new BLE2902());
//為特征添加一個描述

  BLECharacteristic *pCharacteristic = pService->createCharacteristic(CHARACTERISTIC_UUID_RX, BLECharacteristic::PROPERTY_WRITE);
 //創建一個(寫)特征 類型是寫入
  pCharacteristic->setCallbacks(new MyCallbacks());
//為特征添加一個回調

  pService->start();                  //開啟服務
  pServer->getAdvertising()->start(); //服務器開始廣播
  Serial.println("Waiting a client connection to notify...");
}
void setup()
{
  Serial.begin(115200);
  setupBLE("ESP32BLE"); //設置藍牙名稱
}

void loop()
{
  long now = millis(); //記錄當前時間
  if (now - lastMsg > 1000)
  { //每隔1秒發一次信號
    if (deviceConnected && rxload.length() > 0)
    {
      String str = rxload;
      if (str=="10086\r\n")
      {
        const char *newValue = str.c_str();
        pCharacteristic->setValue(newValue);
        pCharacteristic->notify();
      }
    }
    lastMsg = now; //刷新上一次發送數據的時間
  }
}

 下面這個是我感覺可行的程序:

// 包含所必需的庫
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>

BLEServer *pServer = NULL;
BLECharacteristic *pTxCharacteristic;
bool deviceConnected = false;
bool oldDeviceConnected = false;

char BLEbuf[32] = {0};
String data = "";

// 定義收發服務的UUID(唯一標識)
#define SERVICE_UUID           "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"
// RX串口標識
#define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
// TX串口標識
#define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"


class MyServerCallbacks: public BLEServerCallbacks {
    void onConnect(BLEServer* pServer) {
      deviceConnected = true;
    };

    void onDisconnect(BLEServer* pServer) {
      deviceConnected = false;
    }
};

class MyCallbacks: public BLECharacteristicCallbacks {
    void onWrite(BLECharacteristic *pCharacteristic) {
      std::string rxValue = pCharacteristic->getValue();

      if (rxValue.length() > 0) {
        Serial.println("*********");
        Serial.print("Received Value: ");
        for (int i = 0; i < rxValue.length(); i++){
                Serial.print(rxValue[i]);
            }
        Serial.println();
        data =rxValue.c_str();
        //Serial.println(data);
        Serial.println("*********");
        Serial.println();
      }
    }
};

// setup()在復位或上電后運行一次:
void setup() {
  Serial.begin(115200);
  // 初始化藍牙設備
  BLEDevice::init("ESP32 test");
  // 為藍牙設備創建服務器
  pServer = BLEDevice::createServer();
  pServer->setCallbacks(new MyServerCallbacks());
  // 基於SERVICE_UUID來創建一個服務
  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...");
  Serial.println();
}

// loop()一直循環執行:
void loop() {

    if (deviceConnected==1&data.length()>0) {
        memset(BLEbuf, 0, 32);
        memcpy(BLEbuf, data.c_str(), 32);
        Serial.println(BLEbuf);

        pTxCharacteristic->setValue(BLEbuf);   //收到數據后返回數據
        pTxCharacteristic->notify();
        data = "";  //返回數據后進行清空,否則一直發送data
    }

    // 沒有新連接時
    if (!deviceConnected && oldDeviceConnected) {
        // 給藍牙堆棧准備數據的時間
        delay(500);
        pServer->startAdvertising();
        // 重新開始廣播
        Serial.println("start advertising");
        oldDeviceConnected = deviceConnected;
    }
    // 正在連接時
    if (deviceConnected && !oldDeviceConnected) {
        // 正在連接時進行的操作
        oldDeviceConnected = deviceConnected;
    }
}

自己測過的

//LingShun LAB
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>

#include "HX711.h"
/* 連接您的WIFI SSID和密碼 */
#define WIFI_SSID         "hg2020"
#define WIFI_PASSWD       "12345678"
/* 設備的三元組信息*/
#define PRODUCT_KEY       "a17lllJA5zF"
#define DEVICE_NAME       "test2"
#define DEVICE_SECRET     "5bc5928e53557f8d86ac9111550455ba"
#define REGION_ID         "cn-shanghai"
/* 線上環境域名和端口號,不需要改 */ 
#define MQTT_SERVER       "58.250.86.2"
#define MQTT_PORT         2375
#define MQTT_USRNAME      "mqttt"
#define CLIENT_ID         "ESP8266|securemode=3,timestamp=1234567890,signmethod=hmacsha1|"
// 算法工具: http://iot-face.oss-cn-shanghai.aliyuncs.com/tools.htm 進行加密生成password
// password教程 https://www.yuque.com/cloud-dev/iot-tech/mebm5g
#define MQTT_PASSWD       "mqttt"

#define ALINK_BODY_FORMAT         "{\"id\":\"ESP8266\",\"version\":\"1.0\",\"method\":\"thing.event.property.post\",\"params\":%s}"
#define ALINK_TOPIC_PROP_POST     "hgwg01"

unsigned long lastMs = 0;
unsigned char count=0;

HX711 scale;
uint8_t dataPin = 21;
uint8_t clockPin = 22;

float w1, w2, previous = 0;

 
BLECharacteristic *pCharacteristic;
bool deviceConnected = false;
char BLEbuf[32] = {0};
uint32_t cnt = 0;
 
#define SERVICE_UUID           "6E400001-B5A3-F393-E0A9-E50E24DCCA9E" // UART service UUID
#define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
#define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
 
class MyServerCallbacks: public BLEServerCallbacks {
    void onConnect(BLEServer* pServer) {
      deviceConnected = true;
    };
 
    void onDisconnect(BLEServer* pServer) {
      deviceConnected = false;
    }
};
 
class MyCallbacks: public BLECharacteristicCallbacks {
    void onWrite(BLECharacteristic *pCharacteristic) {
      std::string rxValue = pCharacteristic->getValue();
 
      if (rxValue.length() > 0) {
        Serial.print("------>Received Value: ");
 
        for (int i = 0; i < rxValue.length(); i++) {
          Serial.print(rxValue[i]);
        }
        Serial.println();
       
        if (rxValue.find("A") != -1) { 
          Serial.print("Rx A!");
        }
        else if (rxValue.find("B") != -1) {
          Serial.print("Rx B!");
        }
        Serial.println();
      }
    }
};


float temp; //
float lvalue;

void setup() {
  Serial.begin(9600);
  Serial.println("Demo Start");
//  wifiInit();
  unsigned char i=0;
  scale.begin(dataPin, clockPin);
  scale.set_scale(381.95);
  scale.tare();

  Serial.print("UNITS: ");
  Serial.println(scale.get_units(10));
  // Create the BLE Device
  BLEDevice::init("ESP32 BLE Test"); 
  
  // 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_TX, BLECharacteristic::PROPERTY_NOTIFY);
                   
  pCharacteristic->addDescriptor(new BLE2902());
  
  BLECharacteristic *pCharacteristic = pService->createCharacteristic(CHARACTERISTIC_UUID_RX, BLECharacteristic::PROPERTY_WRITE);
  
  pCharacteristic->setCallbacks(new MyCallbacks());
  
  // Start the service
  pService->start();
  
  // Start advertising
  pServer->getAdvertising()->start();
  Serial.println("Waiting a client connection to notify...");
  }

void loop() {
 // read until stable
  w1 = scale.get_units(10);
  delay(100);
  w2 = scale.get_units();
  while (abs(w1 - w2) > 10)
  {
     w1 = w2;
     w2 = scale.get_units();
     delay(100);
  }
  
  Serial.print("UNITS: ");
  Serial.print(w1);
  Serial.println("g");
  if (w1 == 0)
  {
    Serial.println();
  }
  else
  {
    Serial.print("\t\tDELTA: ");
    Serial.println(w1 - previous);
    previous = w1;
  }
  delay(100);
  if (deviceConnected) {
    char param[32];
    sprintf(param, "{\"weight\":%f}",w1);
    memset(BLEbuf, 0, 32);
//    memcpy(BLEbuf, num, sizeof(num)); 
    memcpy(BLEbuf, param, 32); 
    pCharacteristic->setValue(BLEbuf);
    
    pCharacteristic->notify(); // Send the value to the app!
    Serial.print("*** Sent Value: ");
    Serial.print(BLEbuf);
    Serial.println(" ***");
  }
  delay(1000);
}

  


鏈接:https://www.jianshu.com/p/535e6ec3571d
鏈接:https://www.cnblogs.com/GeGeBoom/p/13187387.html

鏈接:https://blog.csdn.net/slimmm/article/details/88638233

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM