Lab 7. Bluetooth Low Energy (BLE)

In this laboratory you will learn how to build a Bluetooth Low Energy (BLE) environmental service on your ESP32 Sparrow boards and to expose the measured sensor data to a Web application.

Bluetooth Smart (Bluetooth Low Energy)

Bluetooth Smart, also known as Bluetooth Low Energy, abbreviated as BLE, is an energy-efficient iteration of Bluetooth designed to conserve power. Its main use involves transmitting small amounts of data over short distances with low bandwidth.

Unlike the constant activity of regular Bluetooth, BLE typically stays in sleep mode, only activating when a connection is established.

This results in significantly lower power consumption, approximately 100 times less than traditional Bluetooth, depending on the specific application. To explore the key distinctions between Bluetooth and Bluetooth Low Energy, refer to the detailed comparison here.

Network Architecture

Within Bluetooth Low Energy, there exist two device types: the server (referred to as peripheral) and the client. The ESP32 is versatile, capable of functioning as either a client or a server.

The server actively broadcasts its presence, making it discoverable by other devices, and it holds data that the client can access. Meanwhile, the client conducts scans of nearby devices. Upon locating the desired server, it initiates a connection and awaits incoming data. This mode of communication is termed point-to-point, and it is the communication mode we will employ with the ESP32 Sparrow.

GATT

GATT, which stands for Generic Attributes, establishes a hierarchical data structure accessible to connected BLE devices. In essence, GATT outlines the protocol governing the exchange of standard messages between two BLE devices. Grasping this hierarchical arrangement is crucial as it facilitates a clearer comprehension of how to effectively employ BLE with the ESP32.

  • Profile: standard collection of services for a specific use case;
  • Service: collection of related information, like sensor readings, battery level, heart rate, etc. ;
  • Characteristic: it is where the actual data is saved on the hierarchy (value);
  • Descriptor: metadata about the data;
  • Properties: describes how the characteristic value can be interacted with. For example: read, write, notify, broadcast, indicate, etc.

BLE Profiles

At the highest level of the hierarchy is a profile, consisting of one or more services. Typically, a BLE device encompasses multiple services.

Each service comprises at least one characteristic, and it may also reference other services. Essentially, a service serves as a repository of information, such as sensor readings.

The Bluetooth Special Interest Group (SIG) has established predefined services for various data types, including Battery Level, Blood Pressure, Heart Rate, Weight Scale, etc. Additional defined services can be explored here.

BLE Characteristic

A characteristic is invariably associated with a service, serving as the location within the hierarchy where the actual data resides (value). It consistently consists of two attributes: the characteristic declaration, offering metadata about the data, and the characteristic value.

Furthermore, the characteristic value may be accompanied by descriptors, providing additional details about the metadata specified in the characteristic declaration.

The properties delineate the ways in which interaction with the characteristic value can occur. Essentially, these properties encompass the operations and procedures applicable to the characteristic:

  • Broadcast
  • Read
  • Write without response
  • Write
  • Notify
  • Indicate
  • Authenticated Signed Writes
  • Extended Properties

UUID

Every service, characteristic, and descriptor possesses a Universally Unique Identifier (UUID), which is a distinct 128-bit (16 bytes) number, for instance: 55072829-bc9e-4c53-938a-74a6d4c78776

Shortened UUIDs are available for all types, services, and profiles outlined in the Bluetooth Special Interest Group (SIG) specifications.

Should your application require a custom UUID, you can generate one using a UUID generator website, but for this lab assignment we will use the default UUID for an Environmental Sensing Service.

In essence, the UUID serves the purpose of uniquely identifying information. For example, it can distinguish a specific service provided by a Bluetooth device.

Project Overview

In our project, we will establish an Environmental Sensing Service featuring three distinct characteristics: one for temperature, another for humidity, and a third for pressure.

The specific temperature, humidity, and pressure readings are stored within the values assigned to their respective characteristics. Each characteristic is configured with the notify property, ensuring that the client receives notifications whenever these values undergo a change.

We will adhere to the default UUIDs designated for the Environmental Sensing Profile and its associated characteristics.

To access the default assigned UUID numbers, visit this page and refer to the Assigned Numbers Document (PDF). By searching for the Environmental Sensing Service within the document, you can explore all the authorized characteristics applicable to this service. It's evident that the Environmental Sensing Service supports temperature, humidity, and pressure readings.

There’s a table with the UUIDs for all services. You can see that the UUID for the Environmental Sensing service is 0x181A.

Then, search for the temperature, humidity, and pressure characteristics UUIDs. You’ll find a table with the values for all characteristics. The UUIDs for the temperature, humidity, and pressure are:

  • pressure: 0x2A6D
  • temperature: 0x2A6E
  • humidity: 0x246F

Mobile App

To verify the proper creation of the BLE Server and to receive notifications for temperature, humidity, and pressure, we'll utilize a smartphone application.

Most contemporary smartphones come equipped with BLE capabilities. You can check your smartphone's specifications to confirm its BLE compatibility.

Note: The smartphone can function as either a client or a server. In this context, it will act as the client, establishing a connection with the Sparrow BLE server.

For our testing purposes, we'll employ a free application named nRF Connect for Mobile, developed by Nordic Semi. This app is available on both Android ( Google Play Store) and iOS. To install the app, simply go to the Google Play Store or App Store, search for “nRF Connect for Mobile,” and proceed with the installation.

Sparrow BLE Service

Here are the steps to create an BLE peripheral with an Environmental Sensing BLE service with temperature, humidity, and pressure, characteristics:

  1. Create a BLE device (server) with a name of your choice (we’ll call it ESP32_BME680, but you can call it any other name).
  2. Create an Environmental Sensing service (UUID: 0x181A).
  3. Add characteristics to that service: pressure (0x2A6D), temperature (0x2A6E) and humidity (0x246F)
  4. Add descriptors to the characteristics.
  5. Start the BLE server.
  6. Start advertising so BLE clients can connect and read the characteristics.
  7. Once a connection is established with a client, it will write new values on the characteristics and will notify the client, every time there’s a change.

Copy the following code to the Arduino IDE, modify it and upload it to your board.

#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
#include "Zanshin_BME680.h" 
 
//BLE server name
#define bleServerName "Sparrow_BME680"
 
// Default UUID for Environmental Sensing Service
// https://www.bluetooth.com/specifications/assigned-numbers/
#define SERVICE_UUID (BLEUUID((uint16_t)0x181A))
 
// Temperature Characteristic and Descriptor (default UUID)
// Check the default UUIDs here: https://www.bluetooth.com/specifications/assigned-numbers/
BLECharacteristic temperatureCharacteristic(BLEUUID((uint16_t)0x2A6E), BLECharacteristic::PROPERTY_NOTIFY);
BLEDescriptor temperatureDescriptor(BLEUUID((uint16_t)0x2902));
 
// Humidity Characteristic and Descriptor (default UUID)
BLECharacteristic humidityCharacteristic(BLEUUID((uint16_t)0x2A6F), BLECharacteristic::PROPERTY_NOTIFY);
BLEDescriptor humidityDescriptor(BLEUUID((uint16_t)0x2902));
 
// Pressure Characteristic and Descriptor (default UUID)
BLECharacteristic pressureCharacteristic(BLEUUID((uint16_t)0x2A6D), BLECharacteristic::PROPERTY_NOTIFY);
BLEDescriptor pressureDescriptor(BLEUUID((uint16_t)0x2902));
 
// Create a sensor object
BME680_Class BME680;
 
bool deviceConnected = false;
 
//Setup callbacks onConnect and onDisconnect
class MyServerCallbacks: public BLEServerCallbacks {
  void onConnect(BLEServer* pServer) {
    deviceConnected = true;
    Serial.println("Device Connected");
  };
  void onDisconnect(BLEServer* pServer) {
    deviceConnected = false;
    Serial.println("Device Disconnected");
  }
};
 
void setup() {
  // Start serial communication 
  Serial.begin(115200);
 
  // Start BME sensor
  while (!BME680.begin(I2C_STANDARD_MODE)) {  // Start BME680 using I2C, use first device found
    Serial.print(F("-  Unable to find BME680. Trying again in 5 seconds.\n"));
    delay(5000);
  }  // of loop until device is located
  Serial.print(F("- Setting 16x oversampling for all sensors\n"));
  BME680.setOversampling(TemperatureSensor, Oversample16);  // Use enumerated type values
  BME680.setOversampling(HumiditySensor, Oversample16);     // Use enumerated type values
  BME680.setOversampling(PressureSensor, Oversample16);     // Use enumerated type values
  Serial.print(F("- Setting IIR filter to a value of 4 samples\n"));
  BME680.setIIRFilter(IIR4);  // Use enumerated type values
  Serial.print(F("- Setting gas measurement to 320\xC2\xB0\x43 for 150ms\n"));  // "degC" symbols
  BME680.setGas(320, 150);  // 320 deg.C for 150 milliseconds
 
  // Create the BLE Device
  BLEDevice::init(bleServerName);
 
  // Create the BLE Server
  BLEServer *pServer = BLEDevice::createServer();
  pServer->setCallbacks(new MyServerCallbacks());
 
  // Create the BLE Service
  BLEService *bmeService = pServer->createService(SERVICE_UUID);
 
  // Create BLE Characteristics and corresponding Descriptors
  bmeService->addCharacteristic(&temperatureCharacteristic);
  temperatureCharacteristic.addDescriptor(&temperatureDescriptor);
 
  bmeService->addCharacteristic(&humidityCharacteristic);
  humidityCharacteristic.addDescriptor(&humidityDescriptor);
 
  bmeService->addCharacteristic(&pressureCharacteristic);
  pressureCharacteristic.addDescriptor(&pressureDescriptor);
 
  // Start the service
  bmeService->start();
 
  // Start advertising
  pServer->getAdvertising()->start();
  Serial.println("Waiting a client connection to notify...");
}
 
void loop() {
  if (deviceConnected) {
 
  static int32_t  temp, hum, pres, gas;  // BME readings
 
  BME680.getSensorData(temp, hum, pres, gas);  // Get readings
 
  float t = (float)((int8_t)(temp / 100));
  t += (float)((uint8_t)(temp % 100))/100.0;
 
  float h = (float)((int8_t)(hum / 1000));
  h += (float)((uint16_t)(hum % 1000)))/1000.0;
 
  float p = (float)((int16_t)(pres / 100));
  p += (float)((uint8_t)(pres % 100))/100.0;
 
    //Notify temperature reading
    uint16_t temperature = (uint16_t)t;
    //Set temperature Characteristic value and notify connected client
    temperatureCharacteristic.setValue(temperature);
    temperatureCharacteristic.notify();
    Serial.print("Temperature Celsius: ");
    Serial.print(t);
    Serial.println(" ºC");
 
    //Notify humidity reading
    uint16_t humidity = (uint16_t)h;
    //Set humidity Characteristic value and notify connected client
    humidityCharacteristic.setValue(humidity);
    humidityCharacteristic.notify();   
    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.println(" %");
 
    //Notify pressure reading
    uint16_t pressure = (uint16_t)p;
    //Set humidity Characteristic value and notify connected client
    pressureCharacteristic.setValue(pressure);
    pressureCharacteristic.notify();   
    Serial.print("Pressure: ");
    Serial.print(p);
    Serial.println(" hPa");
 
    delay(10000);
  }
}

Upload the code to your board. After uploading, open the Serial Monitor, and restart the Sparrow by pressing the RST/EN button.

You should get a “Waiting a client connection to notify…” message in the Serial Monitor.

Then, go to your smartphone, open the nRF Connect app from Nordic, and start scanning for new devices. You should find a device called Sparrow_BME680, this is the BLE server name you defined earlier.

Connect to it. You’ll see that it displays the Environmental Sensing service with the temperature, humidity, and pressure characteristics. Click on the down arrows to activate the notifications.

Then, click on the second icon (the one that looks like a ” mark) at the left to change the format. You can change to unsigned int for all characteristics. You’ll start seeing the temperature, humidity, and pressure values being reported every 10 seconds.

Web BLE Application

Follow the tutorial here to learn how to create a Web application that connects directly to your Sparrow ESP32 board. You can use the web app just like a normal phone application to send and receive information over BLE from your device.

Web BLE is not currently supported by iOS phones

Build the application in the tutorial and deploy the web page in your GitHub account.

Assignment

Modify the web page and the BLE app to display the BME680 sensor data (temperature, pressure and humidity).

iothings/laboratoare/2022/lab7.txt · Last modified: 2023/11/20 22:15 by dan.tudose
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0