Table of Contents

This example will set up the ESP32 as a BLE server with a writable characteristic. The value written to the characteristic will be printed in the serial monitor.

Code for ESP32 (Server):

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

// Define the BLE service and characteristic UUIDs
#define SERVICE_UUID           "12345678-1234-1234-1234-123456789abc"
#define CHARACTERISTIC_UUID    "87654321-4321-4321-4321-abcdef123456"

// Characteristic pointer
BLECharacteristic *pCharacteristic;
BLEServer *pServer;

void setup() {
  // Start Serial Monitor for debugging
  Serial.begin(115200);
  Serial.println("Starting BLE Server...");

  // Initialize BLE device
  BLEDevice::init("Lonely_Binary_ESP32_BLE_Server");

  // Create BLE server
  pServer = BLEDevice::createServer();

  // Create a service
  BLEService *pService = pServer->createService(SERVICE_UUID);

  // Create a writable characteristic
  pCharacteristic = pService->createCharacteristic(
                        CHARACTERISTIC_UUID,
                        BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE
                      );

  // Start the service
  pService->start();

  // Start advertising the BLE server
  BLEAdvertising *pAdvertising = pServer->getAdvertising();
  pAdvertising->start();

  Serial.println("Waiting for client to connect...");
}

void loop() {
  // Nothing to do in the loop, BLE operations are handled in the background
  if (pCharacteristic->getValue().length() > 0) {
    // Print the received value from the client
    Serial.print("Received data: ");
    Serial.println(pCharacteristic->getValue().c_str());

    // Clear the characteristic value after reading
    pCharacteristic->setValue("");  // Reset value
  }
  delay(1000);
}
C++

Explanation:

  1. The ESP32 is initialized as a BLE server with a custom service and a characteristic (READ and WRITE properties).
  2. The client can write a new value to this characteristic, and the server will print the new value in the Serial Monitor.
  3. The server advertises itself so that a BLE client can discover and connect to it.

Client Example (Using a Mobile App like nRF Connect):

  1. Open a BLE client app (such as nRF Connect on Android or iOS).
  2. Scan for nearby BLE devices and find the ESP32_BLE_Server.
  3. Connect to the ESP32 BLE server.
  4. Locate the writable characteristic (87654321-4321-4321-4321-abcdef123456).
  5. Write a new value (e.g., “Hello from client”) to the characteristic.
  6. The ESP32 BLE server will print the received value on the Serial Monitor.

Testing:

When you write a value to the characteristic (e.g., “Lonely Binary”), the ESP32 server will print:

Categorized in:

Bluetooth BLE,

Tagged in: