ESP32 Low Energy Bluetooth BLE Communication

Bluetooth classification

Classic Bluetooth): used for transmission of relatively large amounts of data, such as images, videos, music, etc.

Bluetooth Low Energy: used for products with high real-time requirements but low data rates, such as smart wearable devices, remote controls, mice, keyboards, and data transmission from sensing devices, such as heartbeat belts , blood pressure monitor, temperature and humidity sensor, etc.
Broadcast mode (one-to-many) and networking are also supported.

Bluetooth is divided into single-mode and dual-mode Bluetooth.
Single-mode Bluetooth: only supports classic Bluetooth (EDR/BDR basic rate/enhanced data rate); only supports Bluetooth low energy (BTLE);
dual-mode Bluetooth: supports classic Bluetooth (EDR/BDR) + Bluetooth low energy (BTLE) .

Bluetooth has integrated two standards, classic Bluetooth and low-power Bluetooth since 4.0, not just low-power Bluetooth. Low-power Bluetooth devices and classic Bluetooth devices cannot communicate with each other. If the master device is a low-power Bluetooth device, the slave device must also be a low-power Bluetooth device; similarly, the slave device of classic Bluetooth can only Communicates with the master device of Classic Bluetooth.
Insert image description here

GATT agreement

GATT (Generic Attribute Profile) is part of the Bluetooth Low Energy (BLE) protocol stack, which defines the format and specifications for data exchange between BLE devices.

GATT is based on the concepts of attributes and services. It implements communication between devices by encapsulating data in attributes.

In GATT, a service represents a specific function, and a service can contain multiple attributes. Each attribute has a unique identifier (UUID) that can be used to identify them. Properties can be read-only (Read), writable (Write), notify, broadcast, indicate, etc. Attributes can also contain a descriptor (Descriptor), which is used to describe the characteristics and values ​​of the attribute. Descriptors are optional, but they can provide additional information about the property, such as range, units, or name.

GATT uses a request-response model for communication. When a device wants to read or write a property, it sends a request to another device in a format that contains the UUID of the property to be accessed and the type of operation (read or write). The receiving device returns a response message containing the requested data upon request, or a confirmation message in the case of a write operation. GATT also defines some common attributes and services, such as Device Information Service, Battery Service, etc. These services can make it easier for developers to implement common functions.

The figure below shows an example of the inclusive relationship between concepts at each level of GATT:
Insert image description here

GATT role

In GATT, there are two roles: GATT Server and GATT Client.
Insert image description here

(1) GATT Server
refers to a device with GATT data, which can be connected by GATT Client and provide services. GATT Server stores one or more services, each service contains one or more attributes. When a GATT Client connects to a GATT Server, it can access services and attributes through the GATT protocol. GATT Server needs to respond to GATT Client's requests, such as reading and writing attribute values.
(2) GATT Client
refers to the device that needs to access GATT Server. GATT Client can scan surrounding BLE devices, find devices containing GATT data, and connect to them. Once the connection is established, the GATT Client can read and write services and attributes on the GATT Server through the GATT protocol. For example, GATT Client can read the attribute value of a temperature sensor or write the attribute value of an LED light.

A device can serve as both a GATT Server and a GATT Client. For example, a smart watch can serve as a GATT Server to provide heart rate monitoring services; at the same time, it can also serve as a GATT Client to connect to another device, such as a smartphone, to obtain data from other services, such as notifications from the phone.

Introduction to ESP32 Bluetooth

Insert image description here

The ESP32-WROOM-32 module integrates dual-mode Bluetooth including traditional Bluetooth (BR/EDR), low-power Bluetooth (BLE) and Wi-Fi. It has a wide range of uses: Wi-Fi supports a wide range of communication connections, and Supports direct connection to the Internet through a router; Bluetooth allows users to connect to a mobile phone or broadcast Bluetooth LE Beacon for signal detection.
Bluetooth Features:
• Supports standards Class-1, Class-2 and Class-3 without the need for external power amplifiers
• Enhanced Power Control
• Output power up to +9 dBm
• NZIF receiver with –94 dBm BLE Receiving sensitivity
• Adaptive frequency hopping (AFH)
• Standard HCI based on SDIO/SPI/UART interface
• High-speed UART HCI, up to 4 Mbps
• Supports Bluetooth 4.2 BR/EDR and Bluetooth LE dual-mode controller
• Synchronous connection-oriented/expansion Synchronous connection-oriented (SCO/eSCO)
• CVSD and SBC audio codec algorithms
• Bluetooth Piconet and Scatternet
• Support multi-device connection of traditional Bluetooth and low-power Bluetooth
• Support simultaneous broadcast and scanning
of development boards The integrated Type-C USB to TTL serial port chip CH343 can realize one-click serial port downloading program and serial port printing.

ESP32 development board as BLE service device or scanning device

An ESP32 development board serves as the BLE Server. Arduino IDE opens the BLE_server sample program of the development board and uploads it to the development board.
Insert image description here

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

#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"

void setup() {
    
    
  Serial.begin(115200);
  Serial.println("Starting BLE work!");

  BLEDevice::init("Long name works now");
  BLEServer *pServer = BLEDevice::createServer();
  BLEService *pService = pServer->createService(SERVICE_UUID);
  BLECharacteristic *pCharacteristic = pService->createCharacteristic(
                                         CHARACTERISTIC_UUID,
                                         BLECharacteristic::PROPERTY_READ |
                                         BLECharacteristic::PROPERTY_WRITE
                                       );

  pCharacteristic->setValue("Hello World says Neil");
  pService->start();
  // BLEAdvertising *pAdvertising = pServer->getAdvertising();  // this still is working for backward compatibility
  BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
  pAdvertising->addServiceUUID(SERVICE_UUID);
  pAdvertising->setScanResponse(true);
  pAdvertising->setMinPreferred(0x06);  // functions that help with iPhone connections issue
  pAdvertising->setMinPreferred(0x12);
  BLEDevice::startAdvertising();
  Serial.println("Characteristic defined! Now you can read it in your phone!");
}

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

Insert image description here

Another ESP32 development board acts as a BLE Scanner to scan for Bluetooth devices in the surrounding environment. The Arduino IDE opens the BLE_scan sample program of the development board and uploads it to the development board.

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

#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEScan.h>
#include <BLEAdvertisedDevice.h>

int scanTime = 5; //In seconds
BLEScan* pBLEScan;

class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
    
    
    void onResult(BLEAdvertisedDevice advertisedDevice) {
    
    
      Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str());
    }
};

void setup() {
    
    
  Serial.begin(115200);
  Serial.println("Scanning...");

  BLEDevice::init("");
  pBLEScan = BLEDevice::getScan(); //create new scan
  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster
  pBLEScan->setInterval(100);
  pBLEScan->setWindow(99);  // less or equal setInterval value
}

void loop() {
    
    
  // put your main code here, to run repeatedly:
  BLEScanResults foundDevices = pBLEScan->start(scanTime, false);
  Serial.print("Devices found: ");
  Serial.println(foundDevices.getCount());
  Serial.println("Scan done!");
  pBLEScan->clearResults();   // delete results fromBLEScan buffer to release memory
  delay(2000);
}

Insert image description here

Mobile APP connects to ESP32 as BLE Server

Search, download and install the "nRF Connect for Mobile" software APP on your mobile browser, and connect it to the ESP32 development board as a BLE Sever.
Insert image description here

Summarize

Through this experiment, we learned about the basic concept and simple use of ESP32's BLE. On this basis, ESP32 is equipped with some sensors, which can realize data transmission between two ESP32 or human-computer information interaction between ESP32 and mobile phone through BLE.

Guess you like

Origin blog.csdn.net/qq_42250136/article/details/133077862