Simple BLE Server on ESP32

Exploration of Creating a Server: a simple Bluetooth BLE Server that advertises itself, along with a connectable service that has one read/write characteristic.

The example presented builds using Platformio with the espressif arduino-esp32 core, and leverages the NimBLE-Arduino Bluetooth library.

Project source code

; File: platformio.ini
; PlatformIO Project Configuration File
;
;   Build options: build flags, source filter
;   Upload options: custom upload port, speed and extra flags
;   Library options: dependencies, extra library storages
;   Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html

[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino

monitor_speed=115200

lib_deps = h2zero/NimBLE-Arduino@^1.4.0
// File: main.cpp
// Simple server that advertises itself and its connectable
// service with one read/write characteristic.

#include <Arduino.h>

#include "NimBLEDevice.h"

void setup()
{
    // Initialise the NimBLE library, providing a name for advertisement, or "".
    NimBLEDevice::init("NimBLE");
    
    // Create a Server:
    // Get a pointer to a newly created Server instance.
    NimBLEServer *pServer = NimBLEDevice::createServer();

    // Assign a Service to the Server:
    // Get a pointer to a newly created service instance, identified by
    // the uuid we give the service. It can be 16, 32, or 128 bits.
    NimBLEService *pService = pServer->createService("ABCD");

    // Add a Characteristic to the Service:
    // Get a pointer to a newly created Characteristic instance, identified by
    // a 16, 32, or 128 bit uuid that we give the Characteristic, and with
    // default properties of NIMBLE_PROPERTY::READ | NIMBLE_PROPERTY::WRITE
    NimBLECharacteristic *pCharacteristic = pService->createCharacteristic("1234");
    
    // Start the Service.
    pService->start();

    // Give the Characteristic a value:
    pCharacteristic->setValue("Hello BLE");

    // Create an an Advertisting(er) to solicit connections:
    // Get a pointer to a newly created Advertising(er) instance.
    NimBLEAdvertising *pAdvertising = NimBLEDevice::getAdvertising();

    // Inform the Advertising(er) of the uuid given our Service when created:
    pAdvertising->addServiceUUID("ABCD"); 

    // Begin advertising for connections:
    pAdvertising->start(); 
}

void loop()
{

}

Nordic nRF Connect mobile app screenshots

Prototypical reference: https://github.com/h2zero/NimBLE-Arduino/blob/master/docs/New_user_guide.md#creating-a-server

Suggested reading: https://www.elektor.com/products/develop-your-own-bluetooth-low-energy-applications (no affiliation).


Leave a Reply

Your email address will not be published. Required fields are marked *