ABOUT PORTFOLIO GAMES DEVLOG DOCS TOOLS CONTACT
HOME > DOCS > Embedded / IoT > ESP32 BLE(Bluetooth Low Energy) GATT 서버 구성 및 무선 센서 데이터 Notify 전송Configuring an ESP32 BLE GATT Server and Streaming Sensor Data via Notify
Embedded / IoT Intermediate Arduino ESP32 Core / NimBLE

ESP32 BLE(Bluetooth Low Energy) GATT 서버 구성 및 무선 센서 데이터 Notify 전송Configuring an ESP32 BLE GATT Server and Streaming Sensor Data via Notify

모바일 앱이나 웹 브라우저(Web Bluetooth API)로 저전력 센서 데이터를 20Hz 주기로 푸시 전송하는 ESP32 BLE GATT 서버 구현 가이드입니다.Implementing an ESP32 Bluetooth Low Energy (BLE) GATT server that pushes real-time sensor readings at 20Hz to mobile apps or Web Bluetooth clients using notifications.

#Embedded #ESP32 #BLE #Bluetooth #IoT
핵심 개념BLE 통신에서는 클라이언트(스마트폰·PC)가 주기적으로 읽기 요청을 보내는 폴링(Polling) 방식보다, 센서 값이 갱신될 때 서버(ESP32)가 비동기로 패킷을 전송하는 Notification(알림) 속성이 무선 점유 시간과 전력 소모 면에서 효율적입니다. 이를 위해 캐릭터리스틱에 BLE2902 CCCD(Client Characteristic Configuration Descriptor)를 등록해야 합니다.
Key ConceptIn BLE communication, pushing packets asynchronously from the server (ESP32) via the Notification property whenever sensor data updates consumes less radio airtime and battery power than client-initiated polling. Enabling notifications requires attaching the standard BLE2902 Client Characteristic Configuration Descriptor (CCCD) to the characteristic.

1. ESP32 BLE Notify 서버 아두이노 코드1. ESP32 BLE Notify Server Arduino Implementation

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

#define SERVICE_UUID        "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"

BLECharacteristic *pCharacteristic;
volatile bool deviceConnected = false;

class MyServerCallbacks: public BLEServerCallbacks {
    void onConnect(BLEServer* pServer) override {
        deviceConnected = true;
    }
    void onDisconnect(BLEServer* pServer) override {
        deviceConnected = false;
        // 연결 해제 직후 다시 Advertising을 시작해야 재연결이 가능함
        pServer->getAdvertising()->start();
    }
};

void setup() {
    BLEDevice::init("LYSC_SENSOR_NODE");
    BLEServer *pServer = BLEDevice::createServer();
    pServer->setCallbacks(new MyServerCallbacks());

    BLEService *pService = pServer->createService(SERVICE_UUID);
    pCharacteristic = pService->createCharacteristic(
        CHARACTERISTIC_UUID,
        BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY
    );
    pCharacteristic->addDescriptor(new BLE2902());
    pService->start();

    pServer->getAdvertising()->start();
}

void loop() {
    if (deviceConnected) {
        int sensorVal = analogRead(34);
        pCharacteristic->setValue((uint8_t*)&sensorVal, sizeof(sensorVal));
        pCharacteristic->notify(); // 구독 중인 클라이언트로 패킷 푸시
    }
    delay(50); // 20Hz 전송 주기
}
ble_notify_server.ino
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>

#define SERVICE_UUID        "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"

BLECharacteristic *pCharacteristic;
volatile bool deviceConnected = false;

class MyServerCallbacks: public BLEServerCallbacks {
    void onConnect(BLEServer* pServer) override {
        deviceConnected = true;
    }
    void onDisconnect(BLEServer* pServer) override {
        deviceConnected = false;
        // Restart advertising on disconnect so clients can reconnect
        pServer->getAdvertising()->start();
    }
};

void setup() {
    BLEDevice::init("LYSC_SENSOR_NODE");
    BLEServer *pServer = BLEDevice::createServer();
    pServer->setCallbacks(new MyServerCallbacks());

    BLEService *pService = pServer->createService(SERVICE_UUID);
    pCharacteristic = pService->createCharacteristic(
        CHARACTERISTIC_UUID,
        BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY
    );
    pCharacteristic->addDescriptor(new BLE2902());
    pService->start();

    pServer->getAdvertising()->start();
}

void loop() {
    if (deviceConnected) {
        int sensorVal = analogRead(34);
        pCharacteristic->setValue((uint8_t*)&sensorVal, sizeof(sensorVal));
        pCharacteristic->notify(); // Push packet to subscribed client
    }
    delay(50); // 20Hz transmission interval
}

2. 실무 적용 및 주의사항2. Practical Considerations and Caveats

  • 연결 해제(onDisconnect) 시 Advertising 재시작 필수: BLE 스택은 클라이언트가 한 번 연결되면 자동으로 Advertising(광고 패킷 송출)을 중단합니다. 따라서 onDisconnect 콜백 안에서 pServer->getAdvertising()->start()를 다시 호출하지 않으면 스마트폰 앱에서 재접속할 때 기기가 검색되지 않습니다.
  • 기본 MTU(23바이트) 페이로드 제한 고려: 별도의 MTU 협상(BLEDevice::setMTU)을 거치지 않은 기본 BLE 연결에서는 한 번의 notify()로 보낼 수 있는 실데이터 크기가 최대 20바이트로 제한되므로, 여러 센서 값을 보낼 때는 문자열(JSON) 대신 압축된 C 구조체(struct __attribute__((packed))) 바이너리로 패킹해 전송하는 것이 유리합니다.
  • 메모리 절약을 위한 NimBLE 스택 전환: 기본 Bluedroid 기반 <BLEDevice.h> 라이브러리는 플래시와 SRAM을 많이 점유하므로, Wi-Fi와 동시에 사용하거나 힙 메모리가 부족할 때는 호환 API를 제공하는 경량 NimBLE-Arduino 라이브러리로 대체하는 것을 권장합니다.
  • Restart Advertising inside onDisconnect: The BLE stack stops advertising automatically once a central device connects. Always call pServer->getAdvertising()->start() inside onDisconnect so the node remains discoverable after a link drop.
  • Respect the Default 20-Byte Payload Limit (23-Byte MTU): Without explicit MTU negotiation (BLEDevice::setMTU), a single BLE notification carries at most 20 bytes of payload. Pack multi-axis sensor readings into a binary struct (__attribute__((packed))) rather than verbose JSON strings.
  • Consider NimBLE-Arduino for Lower RAM Footprint: The default Bluedroid-based <BLEDevice.h> stack consumes significant SRAM and flash; switching to the API-compatible NimBLE-Arduino library frees substantial heap space when running alongside Wi-Fi.

GATT 캐릭터리스틱의 BLE2902 디스크립터 구성과 연결 해제 시의 광고 재시작 로직을 갖추면, 모바일 앱이나 Web Bluetooth 대시보드와 안정적으로 실시간 센서 스트림을 주고받을 수 있습니다.

Configuring the BLE2902 descriptor and restarting advertising upon disconnection ensures reliable, low-latency telemetry streaming to mobile apps and Web Bluetooth interfaces.

참고자료 & 관련 링크