yahboom
HomeTutorialsProduct
Solution
Blog
Online Store
About Us
EN/中文
Store
ESP32 Core Board📖
1. ESP32 Introduction
  • 1. ESP32S3 Overview
  • 2. Environment Setup Introduction
  • 3. Dev Board Introduction
2. ESP-IDF Development Tutorial
1. Before Development
  • 1. Environment Setup (Windows)
  • 2. Environment Setup (Linux)
  • 3. Build and Flash
2. Basic Peripherals
  • 1. LED Control
  • 2. Button Detection
  • 3. Peripheral Interrupts
  • 4. ESP_TIMER
  • 5. GPTIMER
  • 6. Watchdog Timer
  • 7. DMA
  • 8. ADC
  • 9. PWM Breathing LED
  • 10. RGB LED Effects
3. Serial Communication and Storage System
  • 1. Serial UART Communication Experiment
  • 2. I2C_OLED Display Experiment
  • 3. SPI Bus Communication Experiment
  • 4. PSRAM External Memory Experiment
  • 5. Flash Read and Write Experiment
  • 6. USB Emulated Mass Storage Experiment
4. FreeRTOS operating system
  • 1.FreeRTOS Core Concepts Theory
  • 2.Task Creation and Management
  • 3.Queue
  • 4.Binary Semaphore
  • 5.Mutex
  • 6.Event Groups
  • 7.Software Timer
  • 8.Task Scheduler
  • 9.Low Power Mode
  • 10.Deadlock
  • 11.Priority Inversion
5. Network Protocols and Wireless Communication
  • 1. WIFI Network Basics
  • 2. WIFI STA Mode
  • 3. WIFI AP Mode
  • 4. UDP Client Experiment
  • 5. UDP Server Experiment
  • 6. TCP Client Experiment
  • 7. TCP Server Experiment
  • 8. Socket Programming Basics
  • 9. HTTP Client Experiment
  • 10. HTTP Server Experiment
  • 11. MQTT IoT Communication Protocol
  • 12. WIFI OTA Upgrade
  • 13. Bluetooth Fundamentals
  • 14. Bluetooth Slave Mode
  • 15. Bluetooth Master Mode
6. Audio Applications
  • 1.I2S Microphone Recording and U-Disk Playback
  • 2.I2S Audio Playback Experiment
  • 3.Repeater Experiment
7. Xiaozhi AI Voice
  • 1. Burn Xiaozhi Firmware
  • 2. Network and Configuration
  • 3. AI Agent Settings
  • 4. Program Analysis
  • 5. Free Chat
3. Arduino Development Course
1. Before Development
  • 1. Environment Setup
  • 2. Build and Flash
2. Basic Peripherals
  • 1. LED Control
  • 2. Button Detection
  • 3. Peripheral Interrupts
  • 4. ESP_TIMER
  • 5. GPTIMER
  • 6. Watchdog Timer
  • 7. ADC
  • 8. PWM Breathing LED
  • 9. RGB LED Effects
3. Serial Communication and Storage System
  • 1. Serial UART Communication
  • 2. I2C OLED Display
  • 3. SPI Bus Communication
  • 4. Flash Read and Write
  • 5. USB Emulated Mass Storage
4. Network Protocols and Wireless Communication
  • 1. WIFI Network Basics
  • 2. WIFI STA Mode
  • 3. WIFI AP Mode
  • 4. UDP Server Experiment
  • 5. UDP Client Experiment
  • 6. TCP Client Experiment
  • 7. TCP Server Experiment
  • 8. HTTP Client Experiment
  • 9. HTTP Server Experiment
  • 10. MQTT IoT Communication Protocol
  • 11. WIFI OTA Upgrade
  • 12. Bluetooth Fundamentals
  • 13. Bluetooth Slave Mode
  • 14. Bluetooth Master Mode
5. Audio Applications
  • 1.I2S Microphone Recording and U-Disk Playback
  • 2.I2S Audio Playback Experiment
  • 3.Repeater Experiment
4. MicroPython Development Course
1. Before Development
  • 1. Environment Setup
  • 2. Build and Flash
  • 3. Thonny IDE
2. Basic Peripherals
  • 1. LED Control
  • 2. Button Detection
  • 3. Peripheral Interrupts
  • 4. TIMER_IT
  • 5. Watchdog Timer
  • 6. ADC
  • 7. PWM Breathing LED
  • 8. RGB LED Effects
3. Serial Communication and Storage System
  • 1. Serial UART Communication Experiment
  • 2. I2C_OLED Display Experiment
  • 3. SPI Bus Communication Experiment
  • 4. Flash Read and Write Experiment
  • 5. Print Storage
4. Network Protocols and Wireless Communication
  • 1. WIFI Network Basics
  • 2. WIFI STA Mode
  • 3. WIFI AP Mode
  • 4. UDP Client Experiment
  • 5. UDP Server Experiment
  • 6. TCP Client Experiment
  • 7. TCP Server Experiment
  • 8. HTTP Client Experiment
  • 9. HTTP Server Experiment
  • 10. MQTT
  • 11. Bluetooth Fundamentals
  • 12. Bluetooth Slave Mode
  • 13. Bluetooth Master Mode
5. Audio Applications
  • 1. I2S Audio Playback Experiment
  • 2. Repeater Experiment
Download
  • Code
  • Hardware_Info
  • 3D_Model_File
  • Software_Tools
  • VMware
  • VM_File
Download ZIP

Welcome to ESP32 Core Board repository

13. Bluetooth Slave Mode

Bluetooth Slave Mode


Bluetooth Slave Mode1. Bluetooth Slave Overview2. Core Concepts2.1 GAP — Generic Access Profile2.2 GATT — Generic Attribute Profile2.3 Notify vs Write2.4 NimBLE-Arduino Library Architecture2.5 Notify vs Indicate Implementation Differences in Arduino3. Hardware Dependencies3.1 ESP32-S3 BLE Hardware Specifications3.2 Required Libraries4. Project Architecture and Flow5. Source Code Analysis5.1 Header Files and Global Variables5.2 Receiving Master Data — WriteCallbacks5.3 Connect/Disconnect Event Callbacks — ServerCallbacks5.4 FreeRTOS Push Task — sendTask5.5 setup() — Initialize BLE Slave5.6 loop() — Empty Loop6. Operation Procedures6.1 Build and Flash6.2 Method 1: Phone Bluetooth Debug6.3 Method 2: Dual-Board Communication Test (Requires Two Boards)6.4 Expected Output — Phone Debug6.5 Expected Output — Dual-Board Communication6.6 Log Field Description6.7 Edge Cases7. FAQ


1. Bluetooth Slave Overview

BLE (Bluetooth Low Energy) is a short-range wireless communication protocol designed for low power consumption and low bandwidth scenarios. Compared to Classic Bluetooth, BLE connections are faster (millisecond-level) and consume less power (coin batteries can run for months).

Importance of BLE Slave Tutorial: BLE Slave (Peripheral) is the most common role for IoT devices — sensor nodes, wearable devices, smart home peripherals, etc. Most scenarios run as slaves. Mastering slave programming means you can build smart devices that can be discovered and connected by phones, tablets, or gateways. This is a core skill for embedded BLE development.

This experiment uses the NimBLE protocol stack (saves ~50% RAM compared to Arduino's default Bluedroid), creating a FreeRTOS task that pushes data to the master every 2 seconds, while also receiving data written by the master.

After completing this tutorial, you will have: An ESP32-S3 development board broadcasting with device name ESP-IDF. Phones or another ESP32-S3 can scan, connect, receive pushed data every 2 seconds, and send arbitrary text commands to the slave — a complete bidirectional BLE communication slave.

Typical Application Scenarios:

Application TypeExample
Sensor SlaveThermometer broadcasts and pushes readings
Wearable DeviceFitness band pushes heart rate data to phone
BeaconiBeacon location broadcast

BLE Role System:

RoleGAP NameResponsibility
SlavePeripheralBroadcasts presence, accepts connections, provides GATT services for master access
MasterCentralActively scans nearby devices, initiates connections, discovers services and characteristics, reads/writes data

2. Core Concepts

2.1 GAP — Generic Access Profile

GAP (Generic Access Profile) defines how BLE devices are scanned and connected.

GAP operations for this slave:

OperationArduino APIDescription
AdvertisingNimBLEDevice::getAdvertising()->start()Periodically sends advertising packets containing device name and service UUID
Connection ResponseServerCallbacks::onConnect()Accepts master connection request, updates connection status
Re-advertising on DisconnectServerCallbacks::onDisconnect() → NimBLEDevice::startAdvertising()Automatically restarts advertising after disconnection

Advertising Packet Structure

Advertising Packet
  ├─ Flags: General discoverable + BR/EDR not supported
  ├─ Name: "ESP-IDF" (Complete)
  │         Complete device name; central matches on this
  └─ Service UUID: 0xFFF0 (Complete List of 16-bit Service UUIDs)
            Custom service UUID; central can determine available services during scan

2.2 GATT — Generic Attribute Profile

GATT (Generic Attribute Profile) defines the data organization structure of BLE devices.

GATT Custom Service Architecture for This Project

xxxxxxxxxx
Service: 0xFFF0 (Custom Primary Service)
  ├─ Characteristic: 0xFFF1
  │     Properties: READ | NOTIFY (Readable + Slave notifies master actively)
  │     Direction: Slave → Master
  │     Purpose: Slave pushes data to central via Notify every 2 seconds
  │
  └─ Characteristic: 0xFFF2
        Properties: WRITE | WRITE_NR (Supports both acknowledged and unacknowledged writes)
        Direction: Master → Slave
        Purpose: Receives data from central, processed in onWrite() callback

2.3 Notify vs Write

OperationInitiatorTargetAcknowledgmentTypical Scenario
NotifySlave → Master0xFFF1No ACKSensor data reporting, heartbeat counting
WriteMaster → Slave0xFFF2WRITE: Requires link layer ACK; WRITE_NR: No ACKControl command delivery, parameter configuration
IndicateSlave → Master(Not used)Requires master ACKCritical data reporting, guaranteed delivery

In this project, the slave sends a fixed message via Notify on 0xFFF1 every 2 seconds; the master can write arbitrary data to 0xFFF2 at any time, and the slave receives and prints it immediately in onWrite(). Both operations are asynchronous and independent, non-blocking.

2.4 NimBLE-Arduino Library Architecture

ESP32-S3 uses Apache NimBLE as the BLE Host protocol stack.

Core Class Hierarchy

xxxxxxxxxx
NimBLEDevice               ← Static class, stack initialization + global control
  ├─ NimBLEServer          ← GATT server, manages service list
  │    ├─ NimBLEService    ← GATT service, contains multiple characteristics
  │    │    └─ NimBLECharacteristic  ← GATT characteristic, data carrier + callback binding
  │    └─ NimBLEServerCallbacks     ← User overrides onConnect/onDisconnect
  ├─ NimBLEAdvertising     ← Advertising parameter config and control
  └─ NimBLECharacteristicCallbacks  ← User overrides onWrite/onRead

Compared to ESP-IDF native NimBLE's callback-style API (gap_event_cb, gatt_svr_access_cb), the Arduino wrapper maps each event type to independent C++ virtual methods implemented through class inheritance. This makes code logic more focused and eliminates the need for switch/case dispatching in a single callback function.

2.5 Notify vs Indicate Implementation Differences in Arduino

In Arduino NimBLEDevice library, the difference between notify and indicate is determined by characteristic properties and send methods together.

OperationProperty DeclarationSend MethodMaster Acknowledgment
NotifyNIMBLE_PROPERTY::NOTIFYpChar->notify()No
IndicateNIMBLE_PROPERTY::INDICATEpChar->indicate()Yes
​x
// Notify — No ACK, suitable for high-frequency sensor data
pCharNotify = pService->createCharacteristic(
    CHAR_NOTIFY_UUID,
    NIMBLE_PROPERTY::READ | NIMBLE_PROPERTY::NOTIFY  // Declare NOTIFY property
);
pCharNotify->setValue("Hello");
pCharNotify->notify();   // Send ATT Handle Value Notification

// Indicate — Requires ACK, suitable for critical control commands
// pChar->indicate();    // Send ATT Handle Value Indication

3. Hardware Dependencies

3.1 ESP32-S3 BLE Hardware Specifications

SpecificationParameter
Wireless StandardBLE 5.0
Max TX Power+20 dBm
Receiver Sensitivity-97 dBm (1Mbps mode)
Max MTU251 bytes (Auto-negotiated by NimBLE-Arduino)
AntennaOn-board PCB antenna
Advertising IntervalProtocol stack default (~100ms)
Protocol StackNimBLE (Apache open source) via NimBLE-Arduino
Arduino TX Power SettingNimBLEDevice::setPower(ESP_PWR_LVL_P3) — Set to +3dBm in this tutorial

BLE and Wi-Fi share the 2.4GHz RF front-end and can coexist through time-division multiplexing.

3.2 Required Libraries

LibraryPurposeInclude Method
NimBLEDevice.hNimBLE BLE protocol stack Arduino wrapper#include <NimBLEDevice.h>

NimBLEDevice library needs to be installed via Arduino IDE library manager: Tools → Manage Libraries → Search "NimBLE" → Install "NimBLE-Arduino" (Author: h2zero). Do not confuse with ESP32's built-in "BLE" library (based on Bluedroid).


4. Project Architecture and Flow

File Structure ([BLE_Slave.ino](../../../Arduino/3.Network%20Communication/BLE_Slave/BLE_Slave.ino), ~90 lines total):

xxxxxxxxxx
BLE_Slave.ino
├─ #include + Macros (DEVICE_NAME, SERVICE_UUID, CHAR_*_UUID)
├─ Global variables (pServer, pCharNotify, g_connected)
├─ class WriteCallbacks         ← Receives master writes (5.2)
├─ class ServerCallbacks        ← Connect/disconnect events (5.3)
├─ void sendTask()              ← FreeRTOS periodic push (5.4)
├─ void setup()                 ← BLE slave initialization six-step method (5.5)
└─ void loop()                  ← Empty loop (5.6)

Program Flow:

xxxxxxxxxx
setup()
  ├─ NimBLEDevice::init("ESP-IDF")                       // Initialize stack
  ├─ createServer() + setCallbacks(serverCb)              // Create GATT server
  ├─ createService(0xFFF0)
  │    ├─ createCharacteristic(0xFFF1, READ|NOTIFY)      // Notify characteristic
  │    └─ createCharacteristic(0xFFF2, WRITE|WRITE_NR)   // Write characteristic + bind callback
  ├─ service.start()
  └─ startAdvertising()                                   // Start advertising

sendTask (FreeRTOS):
  └─ Every 2s: setValue + notify                             // Push data

WriteCallbacks::onWrite():
  └─ Print data received from master

5. Source Code Analysis

Source code: Source code → Arduino → 3.Network Communication → BLE_Slave → BLE_Slave.ino

5.1 Header Files and Global Variables

The top of the file contains #include, macro definitions, and global variables. NimBLEDevice.h is the only header file, which internally aggregates all C++ wrapper classes for the NimBLE protocol stack. Macros use NimBLEUUID((uint16_t)0x...) to wrap 16-bit UUIDs into BLE standard 128-bit UUIDs. Three global variables — server pointer, Notify characteristic pointer, and connection status flag — persist throughout the program lifecycle.

xxxxxxxxxx
// NimBLE BLE stack
#include <NimBLEDevice.h>

// Advertising device name
#define DEVICE_NAME          "ESP-IDF"
// Primary service UUID
#define SERVICE_UUID         NimBLEUUID((uint16_t)0xFFF0)
// Notify char — slave→central
#define CHAR_NOTIFY_UUID     NimBLEUUID((uint16_t)0xFFF1)
// Write char — central→slave
#define CHAR_WRITE_UUID      NimBLEUUID((uint16_t)0xFFF2)

// BLE GATT server pointer
NimBLEServer*        pServer      = nullptr;
// Notify char pointer
NimBLECharacteristic* pCharNotify = nullptr;
// BLE connection status flag
bool                  g_connected  = false;

5.2 Receiving Master Data — WriteCallbacks

WriteCallbacks is responsible for receiving data sent by the master through the Write characteristic (0xFFF2). It inherits from NimBLECharacteristicCallbacks and overrides onWrite(), which NimBLE protocol stack automatically calls each time a master write completes. getValue() returns complete data (std::string), no manual mbuf operation or packet aggregation timer needed.

xxxxxxxxxx
// Callback class for receiving central write data
class WriteCallbacks : public NimBLECharacteristicCallbacks {
  void onWrite(NimBLECharacteristic* pChar, NimBLEConnInfo& connInfo) override {
    // Get data central just wrote
    std::string recvData = pChar->getValue();
    Serial.println("==================================");
    Serial.printf("Host Message: %s\n", recvData.c_str());
    Serial.println("==================================");
  }
} writeCb;  // Global instance, bound when creating characteristic

5.3 Connect/Disconnect Event Callbacks — ServerCallbacks

Connect and disconnect are two critical events in the BLE slave lifecycle. Inherit from NimBLEServerCallbacks and override onConnect and onDisconnect: on connect, set the status flag for the send task; on disconnect, clear the flag first then call startAdvertising() to resume advertising — otherwise the device will be "silent" and the master can never scan it again.

xxxxxxxxxx
// BLE connect/disconnect callbacks class
class ServerCallbacks : public NimBLEServerCallbacks {
  void onConnect(NimBLEServer* pServer, NimBLEConnInfo& connInfo) override {
    // Set connection flag
    g_connected = true;
    Serial.println("Bluetooth connected");
  }

  void onDisconnect(NimBLEServer* pServer, NimBLEConnInfo& connInfo, int reason) override {
    // Clear connection flag
    g_connected = false;
    Serial.println("Bluetooth disconnected");
    // Key: restart advertising for re-discovery
    NimBLEDevice::startAdvertising();
  }
} serverCb;  // Global instance

5.4 FreeRTOS Push Task — sendTask

sendTask is an independent FreeRTOS task that checks connection status every 2 seconds in an infinite loop. If the master is online, it pushes data via the Notify characteristic (0xFFF1). Core logic is only two lines: setValue() updates the local characteristic value cache, notify() triggers ATT Handle Value Notification to the master. When not connected, g_connected is false and the task silently skips.

xxxxxxxxxx
// FreeRTOS periodic send task
void sendTask(void* param) {
  while (1) {
    // Send only when connected and char is valid
    if (g_connected && pCharNotify) {
      // Set characteristic value
      pCharNotify->setValue("Hello from ESP32 Slave");
      // Send notification to central
      pCharNotify->notify();
      Serial.println("Sent: Hello from ESP32 Slave");
    }
    // Block 2 seconds
    vTaskDelay(pdMS_TO_TICKS(2000));
  }
}

5.5 setup() — Initialize BLE Slave

setup() is Arduino's entry point where all one-time initialization is done. The core flow is divided into six steps — initialize stack → create GATT server → create service → create characteristics → start service → start advertising — finally create FreeRTOS task to start periodic sending.

xxxxxxxxxx
void setup() {
  // Init serial + wait for USB enumeration
  Serial.begin(115200);
  delay(1500);
  Serial.println("\n BLE Slave Started!");

  // Init BLE stack + set advertising name
  NimBLEDevice::init(DEVICE_NAME);
  // TX power +3dBm
  NimBLEDevice::setPower(ESP_PWR_LVL_P3);

  // Create GATT server
  pServer = NimBLEDevice::createServer();
  // Register connect/disconnect callbacks
  pServer->setCallbacks(&serverCb);

  // Create custom GATT service
  NimBLEService* pService = pServer->createService(SERVICE_UUID);

  // Create Notify char — slave→central
  pCharNotify = pService->createCharacteristic(
    CHAR_NOTIFY_UUID,
    NIMBLE_PROPERTY::READ | NIMBLE_PROPERTY::NOTIFY
  );

  // Create Write char + chained callback binding
  pService->createCharacteristic(
    CHAR_WRITE_UUID,
    NIMBLE_PROPERTY::WRITE | NIMBLE_PROPERTY::WRITE_NR
  )->setCallbacks(&writeCb);

  // Register service to ATT attribute table
  pService->start();

  // Configure advertising and start
  NimBLEAdvertising* pAdvertising = NimBLEDevice::getAdvertising();
  // Include service UUID in advertising
  pAdvertising->addServiceUUID(SERVICE_UUID);
  // Include device name in advertising
  pAdvertising->setName(DEVICE_NAME);
  // Start advertising (ch 37/38/39)
  pAdvertising->start();

  Serial.println("Waiting for host connection...");

  // Create FreeRTOS periodic send task
  xTaskCreate(sendTask, "sendTask", 2048, NULL, 1, NULL);
}

BLE Slave Initialization Six-Step Method

StepAPIDescription
1. Initialize StackNimBLEDevice::init(DEVICE_NAME)One line completes what takes 5 steps in ESP-IDF; parameter also serves as advertising device name
2. Create ServerNimBLEDevice::createServer()Create NimBLEServer instance, manages GATT attribute table
3. Create ServicepServer->createService(SERVICE_UUID)Create service entry for 0xFFF0 in ATT table
4. Create CharacteristicspService->createCharacteristic(...)Add Notify and Write characteristics to service
5. Start ServicepService->start()Register service + characteristics to ATT; master can discover via GATT
6. Start AdvertisingpAdvertising->start()Periodically send advertising packets on BLE channels 37/38/39

5.6 loop() — Empty Loop

loop() is completely empty in BLE applications. All work is distributed across three independent execution flows; Arduino's main task does not need to intervene.

xxxxxxxxxx
void loop() {}
Execution FlowResponsible ForRunning Location
NimBLE Host TaskProtocol stack event loop, handles GAP advertising/connection/disconnection, dispatches GATT write callbacksAuto-created inside NimBLEDevice::init()
sendTaskPush data via Notify every 2 secondsUser xTaskCreate created
loop()No operation — placeholder onlyArduino main task

6. Operation Procedures

There are two ways to test the slave: choose one. Method 1 (Phone Bluetooth Debug) is suitable when you only have one development board; Method 2 (Dual-Board Communication) requires two ESP32-S3 boards with Slave and Master firmware respectively.

6.1 Build and Flash

Prerequisites: NimBLE-Arduino library installed (Tools → Manage Libraries → Search "NimBLE-Arduino" → Install, author h2zero).

Open Library

Install NimBLE-Arduino Library

Arduino flashing process: See Arduino → 1. Before Development → 2. Build and Flash.

6.2 Method 1: Phone Bluetooth Debug

Applicable Scenario: Only one ESP32-S3 board, using a phone app as BLE master for quick verification.

Recommended Apps: nRF Connect for Mobile (most feature-rich), LightBlue, EFR Connect, BLE Scanner — all free.

Operation Steps:

StepOperationExpected Result
1Power on slaveSerial outputs Waiting for host connection...
2Phone app scansDiscovers device ESP-IDF
3Tap connectSlave serial outputs Bluetooth connected
4Find 0xFFF1, enable notifications (Subscribe)Receives Hello from ESP32 Slave push every 2 seconds
5Find 0xFFF2, write arbitrary textSlave serial prints Host Message: <text>
6Disconnect BluetoothSlave serial outputs Bluetooth disconnected, automatically resumes advertising

nRF Connect Detailed Operation Guide:

  1. Scan for Devices: Open the app, tap Scan, find ESP-IDF in the device list. Note: If not found, pull down to refresh or move closer to the slave and retry.

  2. Connect: Tap Connect next to ESP-IDF. After successful connection, app top shows CONNECTED, bottom tab switches to CLIENT page, slave serial prints Bluetooth connected synchronously.

    手机端搜索ESP-IDF

  3. Discover Services: After connection, app automatically performs GATT service discovery, CLIENT page lists all services. Find Unknown Service with UUID 0xFFF0, tap to expand.

  4. Enable Notifications (Subscribe): After expanding, you see two characteristics:

    1. Unknown Characteristic — UUID 0xFFF1, properties show READ, NOTIFY

    2. Unknown Characteristic — UUID 0xFFF2, properties show WRITE, WRITE NO RESPONSE

  5. Tap the multiple downward arrows icon next to 0xFFF1 (Enable Notifications). After this, the app automatically pops up Hello from ESP32 Slave every 2 seconds.

    手机端页面手机端接收数据

  6. Write Data: Tap the upward arrow icon next to 0xFFF2 (Write). A text input dialog appears. Select Text format, enter any text (e.g., Hello from Phone), tap Send. Slave serial immediately prints Host Message: Hello from Phone.

    手机端发送数据

  7. Disconnect: Tap the top DISCONNECT button to disconnect. Slave serial prints Bluetooth disconnected, while automatically resuming advertising (at this point, immediately tap Scan again, ESP-IDF will reappear in the device list).

    Disconnect

LightBlue users: Similar operation — Scan → Connect → Select service 0xFFF0 → For 0xFFF1 click Listen for notifications → For 0xFFF2 click Write new value.

6.3 Method 2: Dual-Board Communication Test (Requires Two Boards)

Applicable Scenario: Two ESP32-S3 boards, one as BLE Slave, one as BLE Master, achieving complete dual-device communication.

StepOperationExpected Result
1Power on Slave boardSerial outputs Waiting for host connection...
2Power on Master boardMaster scans and auto-connects to ESP-IDF
3Wait for connectionSlave serial outputs Bluetooth connected
4Wait ~2 secondsSlave serial outputs Sent: Hello from ESP32 Slave
5Master writes to 0xFFF2Slave serial prints Host Message: <content>
6Disconnect Master or reset SlaveSerial outputs Bluetooth disconnected

6.4 Expected Output — Phone Debug

Slave Serial:

xxxxxxxxxx
BLE Slave Started!
Waiting for host connection...
Bluetooth connected
Sent: Hello from ESP32 Slave
==================================
Host Message: Hello from Phone
==================================
Sent: Hello from ESP32 Slave
...
Bluetooth disconnected

Serial Output

Phone App Side:

OperationApp Display
ScanDevice list shows ESP-IDF, service UUID 0xFFF0
After connectionShows two characteristics: 0xFFF1 (NOTIFY, READ) and 0xFFF2 (WRITE, WRITE_NR)
Enable 0xFFF1 notificationsPops up Hello from ESP32 Slave every 2 seconds
Write Hello from Phone to 0xFFF2Write successful, Slave serial prints synchronously

6.5 Expected Output — Dual-Board Communication

Slave Serial:

xxxxxxxxxx
BLE Slave Started!
Waiting for host connection...
Bluetooth connected
Sent: Hello from ESP32 Slave
Sent: Hello from ESP32 Slave
==================================
Host Message: Hello from ESP32 Master
==================================
Sent: Hello from ESP32 Slave
...
Bluetooth disconnected

双板测试

Output Rhythm Difference: Slave's sendTask pushes at fixed 2-second intervals and prints immediately, so serial log rhythm is strictly 2 seconds per Sent:. Master's notification reception goes through NimBLE protocol stack's internal event queue, and Master's own periodic task (usually 5-6 seconds) retrieves data from the queue for printing in batches. So Slave prints two or three times before Master prints once in a batch. The frequency mismatch only reflects the difference in their respective print cycles and does not affect BLE transmission itself — every single notification is delivered at the NimBLE underlying layer.

This tutorial only covers Slave-side code. For Master-side implementation and output, please refer to the corresponding BLE Master Tutorial.

6.6 Log Field Description

LogMeaning
BLE Slave Started!Program started, initialization complete
Waiting for host connection...Advertising started, waiting for master scan/connection
Bluetooth connectedMaster successfully connected
Bluetooth disconnectedMaster disconnected, slave automatically re-advertising
Sent: Hello from ESP32 SlaveSlave pushed Notify via 0xFFF1
Host Message: <content>Slave received master's write via 0xFFF2

6.7 Edge Cases

ScenarioBehavior
Slave runs standalone (not connected)Continues advertising, sendTask() silently skips, no data sent
Master disconnectsClears connection flag, calls startAdvertising() to automatically resume advertising
Master rescans after disconnectSlave has already resumed advertising, can be rediscovered and connected
Right after connectionsendTask has 2-second cycle, first Notify delayed by at most 2 seconds
Master rapid consecutive writesEach write is processed independently in onWrite(), no interference

7. FAQ

SymptomCauseSolution
Compilation error: NimBLEDevice.h not foundNimBLE-Arduino library not installed, or wrong BLE library installed (Bluedroid)Library manager search "NimBLE-Arduino" (author h2zero) to install; confirm board selected as ESP32S3 Dev Module; restart IDE
No serial outputUSB CDC On Boot not enabled, or baud rate mismatchTools → USB CDC On Boot → Enabled; serial monitor set to 115200; press RST to reset
Master cannot scan slaveAdvertising not started, already connected by another device, too far or interferenceConfirm serial has Waiting for host connection...; confirm not taken by another connection; move within 5 meters, away from 2.4GHz interference sources; restart phone Bluetooth
Disconnects immediately after connectionIncompatible connection parameters or onConnect() takes too longNormal — onDisconnect() auto re-advertises; if persists, check distance and interference; onConnect() in this tutorial does not timeout
Phone app cannot receive Notify dataNotifications not enabled for 0xFFF1 (CCCD not written 0x0001)nRF Connect tap downward arrows next to 0xFFF1 (Enable Notifications); LightBlue enable "Listen for notifications"
Cannot distinguish pAdvertising->start() vs startAdvertising()Former is called after initial parameter config; latter reuses existing config on disconnectUse pAdvertising->start() for initial advertising in setup(); use NimBLEDevice::startAdvertising() for re-advertising in onDisconnect()
How to modify notification content or interval?—Modify sendTask(): change setValue() content, adjust vTaskDelay() milliseconds. Note power consumption and channel congestion for high frequency
Slave/Master output frequency inconsistentBoth ends' printing driven by their own task cycles, Slave 2s, Master 5-6sNormal — does not affect BLE transmission, every notification is delivered at NimBLE underlying layer
Can Wi-Fi and BLE be used simultaneously?ESP32-S3 supports time-division multiplexing, Arduino core and NimBLE auto-coordinateJust #include <WiFi.h> and <NimBLEDevice.h> together; note throughput decreases for both, audio streaming not recommended with coexistence
Bluetooth Fundamentals
Bluetooth Master Mode

COMPANY

  • About us
  • Team Style
  • Blog

LEARNING & EXPLORATION

  • Tutorials
  • Edge AI hardware
  • Educational robots
  • Embedded intelligent hardware

WHERE TO BUY

  • Yahboom Online Store
  • Amazon
  • Alibaba
  • AliExpress
  • Mercado

TECHNOLOGY SUPPORT

  • Email: support@yahboom.com

BE A DISTRIBUTOR

  • Email: sales@yahboom.com
QR Code

Copyright © 2017-2026 Yahboom. All Rights Reserved.

EN/中文