yahboom
HomeLearn
Solution
Blog
Online Store
About Us
EN/中文
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 Fundamentals

Bluetooth Fundamentals


Bluetooth Fundamentals1. Bluetooth Overview1.1 What is Bluetooth1.2 Bluetooth Version Evolution1.3 Bluetooth Frequency Bands and Channels1.4 Bluetooth vs WiFi2. Bluetooth Protocol Stack Architecture2.1 Dual-Mode Architecture2.2 Host vs Controller Layering2.3 Layer Details3. Classic Bluetooth vs Low Energy Bluetooth3.1 Core Differences3.2 Why BLE Power Consumption is Low4. BLE Core Concepts4.1 GAP — Generic Access ProfileFour GAP Device RolesAdvertising TypesAdvertising Data Format4.2 ATT — Attribute ProtocolAttribute StructureGATT Operations and Permission Correspondence4.3 GATT — Generic Attribute ProfileUUID StructureCCCD — Client Characteristic Configuration Descriptor4.4 Notify vs Indicate Comparison4.5 BLE Connection Parameters5. BLE Advertising and Connection Process5.1 Complete Lifecycle5.2 Advertising Interval and Discovery Delay5.3 BLE 5.0 Extended Advertising6. SM — Security Manager6.1 Pairing Methods6.2 Three Phases of Pairing7. Classic Bluetooth Profile Introduction8. ESP32-S3 Bluetooth Hardware Features8.1 Bluetooth and WiFi Coexistence — 2.4GHz Resource Arbitration8.2 Coexistence Configuration9. ESP-IDF Bluetooth Protocol Stack Selection9.1 Bluedroid vs NimBLE9.2 Protocol Stack Selection9.3 Bluedroid menuconfig Key Configuration10. Common Troubleshooting


1. Bluetooth Overview

1.1 What is Bluetooth

Bluetooth is a short-range wireless communication technology operating in the 2.4 GHz ISM band (2400~2483.5 MHz), used for近距离 data exchange between devices. The name comes from 10th century Nordic King Harald Bluetooth (Harald Blåtann),寓意 unifying communication between different devices.

Key ParameterDescription
Frequency Band2.4000 ~ 2.4835 GHz (ISM license-free band)
ModulationGFSK (Gaussian Frequency Shift Keying), BLE 1M / 2M physical layer
Frequency HoppingAdaptive Frequency Hopping (AFH), 1600 hops/s (classic) / pseudo-random hop (BLE)
Communication DistanceTypical 10m (Class 2, 0~4 dBm), max 100m (Class 1, +20 dBm)
Network TopologyPoint-to-point (Piconet) / Broadcast / Mesh (BLE Mesh)

Bluetooth name comes from Danish King Harald "Bluetooth" Gormson, who unified Scandinavian tribes—as Bluetooth technology aims to unify short-range communication protocols between different devices.

1.2 Bluetooth Version Evolution

VersionYearKey FeaturesMax Speed
1.0 / 1.0B1999First commercial version, serious interoperability issues721 kbps
1.1 / 1.22001~2003AFH adaptive frequency hopping, reduce WiFi interference721 kbps
2.0 + EDR2004Enhanced Data Rate, π/4-DQPSK / 8DPSK modulation2.1 Mbps
2.1 + EDR2007Secure Simple Pairing (SSP), reduce pairing complexity2.1 Mbps
3.0 + HS2009Introduced 802.11 (WiFi) as high-speed channel24 Mbps
4.02010BLE first introduced, low power mode, coin battery can work for months1 Mbps (BLE)
4.1 / 4.22013~2014BLE enhanced: LE Secure Connections, data length extension1 Mbps
5.020162M PHY, LE Long Range (Coded PHY), advertising extensions2 Mbps
5.12019AoA / AoD direction finding (centimeter-level)2 Mbps
5.22020LE Audio, LC3 codec, Isochronous Channels2 Mbps
5.3 / 5.42021~2023Channel classification enhancement, periodic advertising enhancement, PAwR2 Mbps

ESP32-S3 supports BLE 5.0 and Classic Bluetooth (BR/EDR), theoretical max speed: ~1400 kbps application layer throughput under BLE 2M PHY.

1.3 Bluetooth Frequency Bands and Channels

2.4GHz ISM band divides different channel grids by Bluetooth type:

2.4000 GHz                                                2.4835 GHz
   │                                                          │
   ├─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┤
   │  0  │  1  │  2  │ ... │     │     │     │ ... │ 78  │     │  ← BR/EDR: 79 channels, 1MHz spacing
   ├──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┤
   │00│01│02│... │09│10│11│12│13│14│15│16│17│18│19│...│35│36│39│  ← BLE: 40 channels, 2MHz spacing
   └──┴──┴──┴──┴──┴──┴─┬┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┘
                        │
            37 data channels (0~36)  ← Adaptive Frequency Hopping
             3 advertising channels (37@2402, 38@2426, 39@2480 MHz)
Bluetooth TypeChannelsChannel SpacingHop Rate
BR/EDR (Classic Bluetooth)791 MHz1600 hop/s
BLE (Low Energy)40 (37 data + 3 advertising)2 MHzAdaptive pseudo-random

BLE intentionally places advertising channels at 2402 / 2426 / 2480 MHz—these three frequencies avoid WiFi's most commonly used channels 1, 6, 11 (2412 / 2437 / 2462 MHz), physically reducing mutual interference with WiFi.

1.4 Bluetooth vs WiFi

ComparisonBluetooth (BLE 5.0)WiFi (802.11n)
Frequency Band2.4 GHz2.4 GHz / 5 GHz
Channel Bandwidth2 MHz20 / 40 MHz
Max application layer speed~1.4 Mbps~50 Mbps (ESP32-S3)
Power consumptionExtremely low (μA level sleep)Relatively high (mA level continuous receive)
Connection establishment3 ms100 ms ~ several seconds
Typical communication distance10~100m30~100m
Network topologyPoint-to-point / Broadcast / MeshStar (AP + STA)
Applicable scenariosWearables, sensors, audioInternet, video streaming, OTA
IP protocol stackNone (needs upper layer like 6LoWPAN)Native TCP/IP

2. Bluetooth Protocol Stack Architecture

2.1 Dual-Mode Architecture

ESP32-S3 supports dual-mode Bluetooth—the same chip can run classic Bluetooth (BR/EDR) and BLE simultaneously. Both share RF front-end but have independent protocol stacks:

xxxxxxxxxx
┌────────────────────────────────────────────────────────────┐
│                      Application Layer                       │
├──────────────────────────┬─────────────────────────────────┤
│  ┌──────────────────┐   │   ┌──────────────────┐          │
│  │ Classic Bluetooth │   │   │   BLE Profiles   │          │
│  │  SPP / A2DP / HID│   │   │  HID / HRS / BAS │          │
│  └────────┬─────────┘   │   └────────┬─────────┘          │
│           │             │             │                    │
│  ┌────────┴─────────┐   │   ┌────────┴─────────┐          │
│  │   GAP (BR/EDR)   │   │   │   GAP (BLE)      │          │
│  └────────┬─────────┘   │   └────────┬─────────┘          │
│           │             │             │                    │
│  ┌────────┴─────────┐   │   ┌────────┴─────────┐          │
│  │  SDP / RFCOMM    │   │   │  GATT            │          │
│  └────────┬─────────┘   │   │  ATT             │          │
│           │             │   │  SM (Security)   │          │
│  ┌────────┴─────────┐   │   └────────┬─────────┘          │
│  │       L2CAP      │   │   ┌────────┴─────────┐          │
│  └────────┬─────────┘   │   │     L2CAP        │          │
│           │             │   └────────┬─────────┘          │
│           ├──────────────┼─────────────┤                  │
│           │          HCI (Host Controller Interface)        │
│           └──────────────┼─────────────┘                  │
├──────────────────────────┼─────────────────────────────────┤
│  ┌────────┴─────────┐   │   ┌──────────────────┐          │
│  │   Link Manager   │   │   │   Link Layer     │          │
│  │   (LM)           │   │   │   (LL)           │          │  ← Controller
│  ├──────────────────┤   │   ├──────────────────┤          │
│  │      Baseband    │   │   │   Physical Layer │          │
│  ├──────────────────┤   │   │   (PHY)          │          │
│  │   RF / Antenna   │   │   └──────────────────┘          │
│  └──────────────────┘   │                                 │
└──────────────────────────┴─────────────────────────────────┘

2.2 Host vs Controller Layering

Bluetooth protocol stack is divided into two major parts, communicating through HCI (Host Controller Interface):

LayerSub-modulesResponsibilities
HostGAP / GATT / ATT / SM / L2CAP / SDP / RFCOMMProtocol logic, security management, service discovery
HCIUART / USB / SDIO transportStandard communication interface between Host ↔ Controller
ControllerLink Layer / Baseband / PHY / RFRF control, baseband processing, frequency hopping, physical layer modulation/demodulation

On ESP32-S3, Host and Controller run on the same chip, HCI communicates via internal virtual interface (not physical UART). On phones and other devices, Host typically runs on main CPU, Controller is a separate Bluetooth chip.

2.3 Layer Details

LayerFull NameFunctionKey Concepts
PHYPhysical LayerRadio transceiver, GFSK modulation1M / 2M / Coded PHY
LLLink LayerAdvertising, scanning, connection establish/maintain, hoppingAdvertising state / Scanning state / Connection state
HCIHost Controller InterfaceHost ↔ Controller command/event channelCMD / Event / ACL Data
L2CAPLogical Link Control & Adaptation ProtocolData fragmentation/reassembly, protocol multiplexingCID (Channel ID), MTU
SMSecurity ManagerPairing, binding, encryption key distributionJust Works / Passkey / OOB
ATTAttribute ProtocolRead/write/notify protocol for attribute dataAttribute Handle / UUID / Permissions
GATTGeneric Attribute ProfileData organization modelService → Characteristic → Descriptor
GAPGeneric Access ProfileDevice discovery and connection managementAdvertising / Scanning / Connection / Role definition

3. Classic Bluetooth vs Low Energy Bluetooth

3.1 Core Differences

FeatureClassic Bluetooth (BR/EDR)Low Energy Bluetooth (BLE)
Physical channels79 × 1MHz40 × 2MHz
Hop rate1600 hop/sAdaptive (can change channel each connection event)
Connection establishmentScan + Page, ~100msAdvertising → Scanning → Connection, ~3ms
Max application throughput2.1 Mbps~1.4 Mbps (2M PHY)
Power consumptionMedium (~1W active)Extremely low (~0.01~0.5W, coin battery for months)
ConnectionsUp to 7 slaves/piconetNo hard limit (protocol stack implementation dependent)
Data modelSerial emulation (SPP/RFCOMM)Attribute Protocol (ATT/GATT)
Typical applicationsAudio streaming, file transfer, Bluetooth headsetsWearables, sensors, beacons, HID peripherals
Advertising dataLimited (inquiry response)Rich (up to 31 bytes legacy / 1650 bytes extended advertising BLE 5.0)

3.2 Why BLE Power Consumption is Low

BLE's low power consumption comes from three design choices:

Design ChoiceClassic BluetoothBLEPower Impact
Connection duty cycleContinuous pollingConnection interval min 7.5ms, max 4s↓ 99% RF active time
Packet lengthMax 2745 bitsLegacy 376 bits / Extended 2120 bits↓ Transmit duration
Connection latencyNoneCan skip N connection events (Slave Latency)↓ Slave response count
AdvertisingContinuousConfigurable interval 20ms ~ 10.24s↓ Advertising RF duty cycle
xxxxxxxxxx
Classic Bluetooth:  ████████████████████████████████████████████  (RF continuously active)
BLE:                 ██      ██      ██      ██      ██          (Periodic instant active)
                    ↑──────↑ Connection Interval (7.5ms~4s)

BLE's RF is in Sleep state most of the time, only waking for a few milliseconds at predetermined connection events to send/receive data. This is the fundamental reason its power is only 1%~5% of classic Bluetooth.


4. BLE Core Concepts

4.1 GAP — Generic Access Profile

GAP defines how BLE devices are discovered and connected by other devices, and is the entry point for all BLE communication.

Four GAP Device Roles

xxxxxxxxxx
                    Active discovery?
                    │
           ┌────────┴────────┐
           ▼                 ▼
      Yes                 No
           │                 │
     ┌─────┴─────┐     ┌─────┴─────┐
     ▼           ▼     ▼           ▼
  Advertise?  No adv  Advertise?  No adv
     │           │     │           │
     ▼           ▼     ▼           ▼
 Peripheral  Central  Broadcaster  Observer
GAP RoleEnglishSend AdvertisingInitiate ConnectionTypical Devices
PeripheralSlave/Peripheral✅❌Sensors, bracelets, beacons
CentralMaster/Central❌✅Phones, tablets, gateways
BroadcasterBroadcaster✅❌iBeacon, Eddystone beacons
ObserverObserver❌❌Passive listeners, packet sniffers

Advertising Types

Advertising PDU TypeMeaningConnectableScannable
ADV_INDGeneral advertising indication✅ Connectable✅ Scannable
ADV_DIRECT_INDDirected connection advertising (specified target address)✅ Connectable❌
ADV_NONCONN_INDNon-connectable advertising (pure beacon)❌❌
ADV_SCAN_INDScannable advertising (no connect but can get more data)❌✅

Advertising Data Format

Advertising data is organized in Length-Type-Value (LTV) structure:

xxxxxxxxxx
Advertising packet (max 31 bytes / legacy mode)
  ├─ [L=2] [T=Flags]            [V=0x06]                    ← 3 bytes
  ├─ [L=9] [T=Complete Name]    [V="ESP-IDF"]               ← 11 bytes
  ├─ [L=3] [T=16-bit Service]   [V=0xFFF0]                  ← 5 bytes
  └─ [L=...] Other fields...
AD TypeValueDescription
0x01FlagsDiscoverable mode + BR/EDR support flags
0x02 / 0x03Incomplete / Complete 16-bit Service UUIDsService UUID list
0x08 / 0x09Shortened / Complete Local NameDevice name
0x0ATX Power LevelTransmission power (dBm), used for distance estimation
0xFFManufacturer Specific DataManufacturer custom data (used by iBeacon)

4.2 ATT — Attribute Protocol

ATT (Attribute Protocol) is the foundation of BLE data transmission. All data on BLE devices is stored as attributes (Attribute), each attribute is a data unit with handle and UUID.

Attribute Structure

xxxxxxxxxx
Attribute Handle   UUID            Permissions    Value
─────────────────────────────────────────────────────────
  0x0010          0x2800          R              0xFFF0       ← Service declaration
  0x0011          0x2803          R              NOTIFY, 0xFFF1  ← Characteristic declaration
  0x0012          0xFFF1          R|N            "Hello"      ← Characteristic value
  0x0013          0x2902          R|W            0x0001       ← CCCD descriptor

Four elements of each attribute:

ElementDescriptionExample
Attribute Handle16-bit unique number, allocated by protocol stack0x0010
Attribute Type (UUID)Type identifier of attribute0x2800 = GATT Primary Service declaration
PermissionsAccess permissions (read/write/notify/encrypt)Read + Notify
ValueAttribute value (fixed or variable length)"Hello World"

GATT Operations and Permission Correspondence

Operation (ATT layer)GATT MethodDirectionDeclaration Required
Read Request / Responseread_cb()Client ← ServerBLE_GATT_CHR_F_READ
Write Request / Responsewrite_cb()Client → ServerBLE_GATT_CHR_F_WRITE
Write Command (no response)write_cb()Client → ServerBLE_GATT_CHR_F_WRITE_NO_RSP
Handle Value Notificationnotify()Server → ClientBLE_GATT_CHR_F_NOTIFY
Handle Value Indicationindicate()Server → Client (needs confirmation)BLE_GATT_CHR_F_INDICATE

4.3 GATT — Generic Attribute Profile

GATT (Generic Attribute Profile) is built on ATT, defining the hierarchical organization model for BLE data:

xxxxxxxxxx
Profile (Specification/Application layer, e.g. Heart Rate Profile)
  │
  └─ Service (UUID 16/32/128-bit)
      │  e.g.: 0x180D = Heart Rate Service (SIG standard)
      │         0xFFF0 = Custom service
      │
      └─ Characteristic (unit that actually exposes data)
          │  UUID + property declaration (Read/Write/Notify/Indicate)
          │  e.g.: 0x2A37 = Heart Rate Measurement (notification-oriented)
          │         0xFFF1 = Custom notification characteristic
          │
          └─ Descriptor (metadata of characteristic, optional)
              e.g.: 0x2902 = CCCD (Client Characteristic Configuration Descriptor)
                  0x2901 = Characteristic User Description (characteristic name readable text)

UUID Structure

UUID TypeLengthFormatExample
16-bit UUID (SIG standard)2 bytes0xXXXX0x180D (Heart Rate Service)
32-bit UUID4 bytes0xXXXXXXXX0x12345678
128-bit UUID (custom)16 bytesXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX4fafc201-1fb5-459e-8fcc-c5c9c331914b

16-bit UUIDs are standardized identifiers allocated by Bluetooth SIG alliance and require purchase authorization. Custom projects can freely use 128-bit UUIDs, or use non-reserved 16-bit UUIDs (like 0xFFF0~0xFFFE, for development testing only).

CCCD — Client Characteristic Configuration Descriptor

CCCD (Client Characteristic Configuration Descriptor) UUID = 0x2902, is the most critical descriptor in GATT, controlling slave notification/indication toggle:

xxxxxxxxxx
Master enables notification:  Master → CCCD (0x2902) → Write 0x0001 → Slave starts pushing Notify
Master disables notification: Master → CCCD (0x2902) → Write 0x0000 → Slave stops pushing
┌────────────────────────────────────────────────────────────────┐
│ CCCD Value       Meaning                                      │
├────────────────────────────────────────────────────────────────┤
│ 0x0000       Disable all notifications/indications             │
│ 0x0001       Enable notification (Notify)                      │
│ 0x0002       Enable indication (Indicate)                     │
└────────────────────────────────────────────────────────────────┘

4.4 Notify vs Indicate Comparison

ComparisonNotifyIndicate
Wait for acknowledgment after sending❌ No wait✅ Wait for application layer ACK
Send speedFast (no acknowledgment wait)Slow (wait for ACK each time)
ReliabilityLow (lost packets not retransmitted, except link layer retransmission)High (application layer acknowledgment + retransmission)
Typical scenarioHigh-frequency sensor reporting (heart rate, temperature)Critical commands (alarm, switch control)
xxxxxxxxxx
Notify flow:              Indicate flow:
  Slave ──data──→ Master       Slave ──data──→ Master
  (no ack, continue sending)        ←──ACK──
                               Slave sends next only after receiving ACK

4.5 BLE Connection Parameters

After BLE connection is established, master can request modifications to these connection parameters:

ParameterRangeDefaultDescription
Connection Interval7.5ms ~ 4s~30msInterval between two connection events, determines throughput and power consumption
Slave Latency0 ~ 4990Number of connection events slave can skip, reduces slave power consumption
Supervision Timeout100ms ~ 32s~2sHow long without receiving data to determine disconnection
xxxxxxxxxx
Connection interval 7.5ms:  ██ ██ ██ ██ ██ ██ ██ ██  (high throughput, high power)
Connection interval 100ms:  ██     ██     ██     ██   (medium)
Connection interval 1000ms: ██           ██          (low throughput, extremely low power)

Connection interval = 7.5ms × N (N range 6~3200). Smaller value means higher throughput but higher power consumption; larger value means lower power but increased latency. Common sensor scenarios use 100ms~1s; audio scenarios require ≤30ms.


5. BLE Advertising and Connection Process

5.1 Complete Lifecycle

xxxxxxxxxx
Peripheral (Slave)                             Central (Master)
──────────────                               ────────────
  [Standby]                                   [Standby]
     │                                            │
     ▼                                            │
  Advertising ◄── ADV_IND ────────── Scan ────────┘
  (periodic adv)    Adv data: Flags + Name + UUID    (passive or active scan)
     │
     │           ◄── CONNECT_IND ────── Connect
     │               Connection params: Interval + Latency + Timeout
     ▼
  Connected ════════════════════════ Connected ═══
     │                                            │
     │           ◄── Exchange MTU ───            │
     │           ◄── Discover Services ──         │
     │           ◄── Discover Characteristics ──  │
     │           ◄── Enable CCCD ─────            │
     │                                            │
     │           ◄══ Notify/Write ════►           │
     │                                            │
     ▼                                            ▼
  Disconnected                               Disconnected
  (re-advertise)

5.2 Advertising Interval and Discovery Delay

Smaller advertising interval means faster discovery but higher power:

Advertising IntervalAvg Discovery DelayAvg PowerApplicable Scenario
20ms (fast adv)~10ms~1.5mAInitial provisioning stage
100ms~50ms~0.4mANormal connectable state
1s (slow adv)~500ms~0.05mALong standby, beacons

Android/iOS have scan window limitations—iOS background scans about once every 1~2s, so advertising interval should not be greater than 500ms, otherwise phone may take a long time to discover the device. Some systems also require specific Service UUID in advertising data for App background filtering.

5.3 BLE 5.0 Extended Advertising

BLE 5.0 introduced extended advertising mechanism, greatly increasing advertising data capacity from 31 bytes:

​x
Legacy advertising (BLE 4.x):
  3 advertising channels, each ≤ 31 bytes payload

Extended advertising (BLE 5.0):
  Supports carrying advertising data on 37 data channels (not on advertising channels),
  can chain-send multiple packets (max 1650 bytes payload)

  Applications: Indoor navigation, asset tracking, electronic price tag batch updates

6. SM — Security Manager

6.1 Pairing Methods

BLE Security Manager (SM) handles pairing and bonding between devices:

Pairing MethodSecurityUser InteractionApplicable Scenario
Just WorksLow (no MITM protection)No interaction neededSensors without UI (temperature/humidity meter)
Passkey EntryMediumOne party displays 6-digit number, other entersKeyboard connecting to phone, phone with screen device
Numeric ComparisonHigh (LE Secure Connections)Both display 6-digit number, user confirms matchBLE 4.2+ recommended, phone connecting to peripherals
Out of Band (OOB)HighestKey passed through external channel like NFC/QR codeEnterprise security, access control systems

6.2 Three Phases of Pairing

xxxxxxxxxx
Phase 1: Feature Exchange
  Both sides exchange IO Capabilities (display/keyboard presence), security requirements
    → Negotiate pairing method (Just Works / Passkey / OOB)

Phase 2: Key Generation
  STK (Short Term Key, legacy pairing, BLE 4.0/4.1)
  or LTK (Long Term Key, LE Secure Connections, BLE 4.2+)
    → Establish encrypted link

Phase 3: Key Distribution
  LTK + IRK (Identity Resolving Key) + CSRK (Connection Signature Resolving Key)
    → Bonding complete, subsequent reconnections auto-encrypt (no pairing again)

Pairing ≠ Bonding. Pairing is a one-time encryption process; bonding stores keys in NVS flash, subsequent connections auto-encrypt—this is the "paired devices list" in Flutter/Android App.


7. Classic Bluetooth Profile Introduction

Although BLE is mainstream for IoT, ESP32-S3 also supports classic Bluetooth, usable for these classic profiles:

ProfileFull NameTypical ApplicationESP32-S3 Support
SPPSerial Port ProfileWireless serial passthrough—simulate UART replacing wired serial✅ Most commonly used
A2DPAdvanced Audio Distribution ProfileBluetooth audio streaming (headphones, speakers)✅
AVRCPAudio/Video Remote Control ProfileBluetooth remote control (prev/next/volume)✅
HIDHuman Interface DeviceBluetooth keyboard/mouse/gamepad✅
HFPHands-Free ProfileCar hands-free calling✅

SPP is the most commonly used profile in ESP32-S3 classic Bluetooth development—establishes virtual serial port between two devices via RFCOMM serial emulation protocol, appears to upper layer code as byte stream send/receive, similar to UART but without physical wiring. Applicable to wireless debugging, passthrough control, data acquisition, etc.


8. ESP32-S3 Bluetooth Hardware Features

FeatureParameter
Bluetooth StandardBLE 5.0 + BR/EDR (Classic)
Operating Frequency2.4 GHz ISM
Max TX Power+20 dBm (Class 1)
Max RX Sensitivity-97 dBm (BLE 1M)
BLE Max Throughput~1.4 Mbps (2M PHY, ~700 kbps application layer)
Classic Bluetooth Max Speed2.1 Mbps (EDR)
AntennaOnboard PCB ceramic antenna / IPEX external antenna
Protocol StackBluedroid (full) / NimBLE (BLE only)

8.1 Bluetooth and WiFi Coexistence — 2.4GHz Resource Arbitration

Bluetooth and WiFi share the same antenna and 2.4GHz RF front-end—they cannot transmit simultaneously. ESP32-S3 resolves conflicts through Time Division Multiplexing (TDM):

xxxxxxxxxx
WiFi:   ████████░░░░░░░░░░████████░░░░░░░░░░
BLE:    ░░░░░░░░████░░░░░░░░░░░░░░████████░░
        ├──────────┼──────────┼──────────┼──
        Time Slot (coexistence module arbitrates)
Coexistence StrategyDescription
ESP_COEX_PREFER_WIFIWiFi preferred, Bluetooth actively yields on conflict → BLE throughput decreases but WiFi smooth
ESP_COEX_PREFER_BTBluetooth preferred, WiFi TCP ACK may be delayed → BLE connection stable but WiFi may stutter
ESP_COEX_PREFER_BALANCEBalanced mode, dynamic arbitration

In practice, if BLE connection interval is ≥30ms (medium/low throughput scenarios), WiFi and BLE can "peacefully coexist"—BLE occupies predetermined connection event slots (few milliseconds), remaining time WiFi uses RF freely. High-frequency BLE (approaching limit throughput ~700kbps) or dense WiFi transmission (TCP stream, OTA) will interfere with each other; need to tune coexistence strategy or stagger usage periods.

8.2 Coexistence Configuration

Configure coexistence strategy in menuconfig:

xxxxxxxxxx
Component config → Bluetooth → Bluedroid → Bluetooth Coexistence

Or adjust at runtime in code:

xxxxxxxxxx
// Set coexistence mode to balance
esp_coex_set_preferred_mode(ESP_COEX_PREFER_BALANCE);

9. ESP-IDF Bluetooth Protocol Stack Selection

9.1 Bluedroid vs NimBLE

ESP-IDF provides two Bluetooth Host protocol stacks:

Comparison DimensionBluedroidNimBLE
Bluetooth TypeDual-mode (BR/EDR + BLE)BLE only
ROM Usage~512 KB~32 KB
RAM Usage~120 KB (minimum)~4.5 KB
Feature completenessFull: SPP, A2DP, HID, GATT full featuresLean: GAP + GATT only, BLE 5.0 main features
Configuration complexityHigh, many menuconfig optionsLow, init ~10 lines of code
Applicable scenariosNeed classic Bluetooth (audio, SPP passthrough) or full BLE featuresBLE only, code/ram sensitive scenarios
ESP-IDF default✅ Default enabledNeed manual selection

9.2 Protocol Stack Selection

xxxxxxxxxx
Need classic Bluetooth (SPP/A2DP/HID)?  ──Yes──→ Bluedroid (only choice)
       │
       No (BLE only)
       │
       ├── Need full BLE features (Mesh, Extended Advertising, LE Audio)?
       │      ──Yes──→ Bluedroid
       │
       └── Lean BLE peripheral/central role, code/ram sensitive?
              ──Yes──→ NimBLE

Subsequent BLE slave and master experiments in this project all use NimBLE protocol stack. For IoT teaching scenarios requiring only BLE peripheral/central roles, NimBLE's code and memory overhead is much smaller than Bluedroid, making it a more suitable choice.

9.3 Bluedroid menuconfig Key Configuration

When using Bluedroid, must configure:

xxxxxxxxxx
Component config → Bluetooth
  ├─ [*] Bluetooth
  ├─ Bluetooth Host → Bluedroid
  └─ Bluedroid Options
      ├─ [*] Include GATT
      ├─ [ ] Include Classic Bluetooth (as needed)
      └─ [*] Enable BLE 5.0 features (as needed)

When using NimBLE:

xxxxxxxxxx
Component config → Bluetooth
  ├─ [*] Bluetooth
  ├─ Bluetooth Host → NimBLE
  └─ Bluetooth Controller → BLE Only

10. Common Troubleshooting

SymptomCauseSolution
Crash after Bluetooth initNVS not initialized or partition corruptedAdd try-erase logic to nvs_flash_init(); or IDE erase entire flash
Advertising start fails rc=12BLE controller not enabledmenuconfig ensure CONFIG_BT_ENABLED=y, controller mode = BLE Only
Phone can't scan ESP32-S3Advertising interval too large / no Service UUIDReduce advertising interval to ≤100ms; confirm advertising data includes Flags + Name
Disconnects immediately after connection (0~2s)Connection parameters incompatible / too farMove closer (≤5m); confirm no strong WiFi co-frequency interference
WiFi frequent disconnects during BLE connection2.4G RF conflictAdjust coexistence strategy to ESP_COEX_PREFER_WIFI; or increase BLE connection interval to ≥100ms
iOS background scan can't find deviceiOS doesn't notify App about advertising without Service UUIDAdd specified Service UUID in advertising data (iOS App needs to declare corresponding background mode)
Can't discover custom GATT serviceNimBLE service table definition errorConfirm ble_gatt_svc_def array ends with {0,}, UUID format correct
Notify won't sendCCCD not enabled / conn_handle invalidConfirm master wrote CCCD = 0x0001; confirm conn_handle matches current connection
ATT write not permitted logWrote to characteristic value handle without Write permissionConfirm write targets CCCD descriptor handle not characteristic value handle; or add Write flag to characteristic declaration
Bluetooth interrupt during OTAUnderlying restart during OTA causes Bluetooth driver resetAfter OTA complete, re-nvs_flash_init() + re-nimble_port_init()
WIFI OTA Upgrade
Bluetooth Slave 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
QR Code

Copyright © 2017-2026 Yahboom. All Rights Reserved.

EN/中文