Bluetooth Classic
About
The BluetoothSerial library provides a UART-like interface over Bluetooth Classic Serial Port Profile (SPP) for the ESP32. It extends the Arduino Stream class, making it a drop-in replacement for Serial in many applications.
Note
Bluetooth Classic is supported on the original ESP32. On ESP32-S31 the prebuild enables NimBLE only, so BluetoothSerial requires using Arduino as an ESP-IDF component or rebuilding the static libraries.
For more information, see the Arduino as an ESP-IDF component documentation or the
Lib Builder documentation, respectively.
It is not available on ESP32-S2, ESP32-S3, ESP32-C3, ESP32-C6, ESP32-H2, or ESP32-P4.
Key features:
Stream-compatible API (
read(),write(),available(),print(),println())Initiator (master) and acceptor (slave) modes
Multi-client acceptor: several SPP clients at once, with per-peer
writeTo()/onPeerData()Secure Simple Pairing (SSP) with
std::functioncallbacksLegacy PIN pairing via
setPin()Device discovery (synchronous and asynchronous)
Bond management (list and delete bonded devices)
RAII resource management with
std::unique_ptr<Impl>(PIMPL pattern)BTStatusreturn values for error handling on most operations
Architecture
BluetoothSerial follows the PIMPL (Pointer to Implementation) pattern. The public header declares only the API surface while all Bluedroid-specific state lives behind a private struct Impl held by std::unique_ptr<Impl>.
Ownership semantics
The class is not copyable – copy constructor and copy-assignment are
= delete.It is movable – move constructor and move-assignment are
= default, transferring sole ownership of theImplviastd::unique_ptr.
RAII lifecycle
FreeRTOS resources (queues, semaphores, task handles) are allocated inside begin() and released in end() or the destructor. Because allocation can fail, begin() returns BTStatus – check for BTStatus::NoMemory or BTStatus::Timeout to detect resource-creation failures.
Thread safety
SPP callbacks (data received, authentication events) execute on the Bluetooth controller task, while user code runs on the Arduino loop() task. Shared state is protected by FreeRTOS primitives inside the Impl struct. Avoid blocking the BT task in callbacks.
explicit operator bool
BluetoothSerial provides explicit operator bool() const. It returns true when the Bluetooth stack has been initialized successfully (i.e., begin() returned BTStatus::OK). Because the conversion is explicit, implicit boolean conversions are not allowed; use if (static_cast<bool>(SerialBT)) or simply if (SerialBT.connected()).
Design notes
ESP32 and ESP32-S31 – Bluetooth Classic (BR/EDR) hardware is present on the original ESP32 and on ESP32-S31. On ESP32-S31,
BluetoothSerialrequires using Arduino as an ESP-IDF component or rebuilding the static libraries. See the Arduino as an ESP-IDF component documentation or the Lib Builder documentation, respectively.SPP profile – Communication uses the Serial Port Profile, which provides a virtual serial link over L2CAP/RFCOMM.
Security – Both server (acceptor) and client (initiator) modes use
ESP_SPP_SEC_AUTHENTICATE. Incoming and outgoing connections require authentication.Fallible resource creation –
begin()may returnBTStatus::NoMemory(FreeRTOS allocation failure) orBTStatus::Timeout(controller did not respond in time). Always check the return value.
Getting Started
#include <BluetoothSerial.h>
BluetoothSerial SerialBT;
void setup() {
Serial.begin(115200);
SerialBT.begin("ESP32-BT");
Serial.println("Bluetooth started! Pair and connect from your device.");
}
void loop() {
if (Serial.available()) {
SerialBT.write(Serial.read());
}
if (SerialBT.available()) {
Serial.write(SerialBT.read());
}
}
Build requirements
BluetoothSerial is compiled only when Bluetooth is enabled in sdkconfig: SOC_BT_SUPPORTED, CONFIG_BT_ENABLED, and CONFIG_BLUEDROID_ENABLED must be set. SPP must be enabled (CONFIG_BT_SPP_ENABLED) for serial bridge use cases.
Bluetooth memory reservation
The Bluetooth controller and host need dedicated RAM regions. Sketches that do not use Bluetooth should not pay for them, so initArduino() releases those regions back to the heap before setup() runs unless something in the link tells the core that Bluetooth is in use.
Linking this library is enough to make that decision: BluetoothSerial.cpp includes esp32-hal-alloc-bt-classic-mem.h, whose constructor marks Bluetooth Classic as in use before app_main(). If you only ever call the BluetoothSerial API, the regions stay reserved and there is nothing to configure.
If your sketch calls ESP-IDF Bluetooth APIs directly instead of going through an Arduino library, add the matching include yourself in at least one source file, or initialization will fail once the RAM has already been reclaimed:
Bluetooth Classic:
esp32-hal-alloc-bt-classic-mem.hBLE:
esp32-hal-alloc-ble-mem.h
#include "esp32-hal-alloc-bt-classic-mem.h"
Reserving one transport does not reserve the other, so a sketch that drives both stacks directly needs both includes.
API Reference
Lifecycle
begin
Initialize Bluetooth and start SPP.
BTStatus SerialBT.begin(const String &localName = "ESP32", bool isInitiator = false);
localName: Device name visible during discovery and to remote peers.isInitiator: Iftrue, operates in master (initiator) mode and may connect outbound to other devices; iffalse, operates as acceptor (slave) and waits for incoming connections.
Returns BTStatus::OK on success, BTStatus::NoMemory or BTStatus::Timeout on failure.
end
Stop Bluetooth and release resources.
void SerialBT.end(bool releaseMemory = false);
releaseMemory: Whentrue, releases additional internal allocations where applicable.
Stream interface
BluetoothSerial extends Stream, providing:
int SerialBT.available();
int SerialBT.read();
size_t SerialBT.write(uint8_t c);
size_t SerialBT.write(const uint8_t *buf, size_t len);
int SerialBT.peek();
void SerialBT.flush();
All standard print() and println() methods from Print/Stream are available.
Note
flush() waits until the TX queue drains but does NOT wait for data to be acknowledged
on the wire. Bytes may still be in-flight when flush() returns.
Note
In acceptor multi-client mode, write() / print() send to every connected peer.
Use writeTo(address, ...) to target one client. Incoming bytes from all peers are merged
into the single Stream receive buffer; use onPeerData when you need the source address.
Connection
connect
Connect to a remote device. Only used in initiator (master) mode after begin(..., true).
BTStatus SerialBT.connect(const String &remoteName, uint32_t timeoutMs = 10000);
BTStatus SerialBT.connect(const BTAddress &address, uint8_t channel = 0);
remoteName: Friendly name inquiry;timeoutMsbounds how long to wait for a match.address: Bluetooth address of the peer;channelselects the RFCOMM channel when non-zero.
Returns BTStatus (for example BTStatus::OK, BTStatus::Timeout, BTStatus::NotFound).
disconnect
BTStatus SerialBT.disconnect();
BTStatus SerialBT.disconnect(const BTAddress &address);
disconnect()– disconnects all active SPP sessions (or the single initiator link).disconnect(address)– drops one connected peer in acceptor (multi-client) mode.
Returns BTStatus::OK on success, BTStatus::Timeout if the disconnection did not complete
within the internal timeout, or BTStatus::NotFound if the address is not connected.
connected
bool SerialBT.connected() const;
Returns true when at least one SPP link is established.
hasClient
bool SerialBT.hasClient() const;
Equivalent to connected() in the current implementation; provided for readability in server-style sketches.
Multi-client (acceptor)
In acceptor (slave) mode, multiple SPP clients may connect at once. As a single Arduino Stream,
write() / print() broadcast to every connected peer and read() / available() drain
one merged RX buffer. Additive APIs attribute traffic per peer. Initiator (master) connect()
remains one link.
See the MultiClientSerial example. The BLE Nordic-UART equivalent is BLEStream
(libraries/BLE, MultiClientUART example).
peerCount / peers
size_t SerialBT.peerCount() const;
std::vector<BTAddress> SerialBT.peers() const;
peerCount()– number of currently connected clients.peers()– snapshot of connected peer addresses.
writeTo
size_t SerialBT.writeTo(const BTAddress &address, const uint8_t *buf, size_t len);
Sends len bytes to a single connected peer. Returns the number of bytes queued, or 0 if the
peer is not connected or the write fails.
Device discovery
discover (synchronous)
Performs a blocking inquiry and returns accumulated results when discovery completes or times out.
std::vector<BluetoothSerial::DiscoveryResult> SerialBT.discover(uint32_t timeoutMs = 10000);
Each DiscoveryResult contains:
struct DiscoveryResult {
BTAddress address;
String name;
uint32_t cod = 0; // Class of Device
int8_t rssi = -128;
};
discoverAsync
Starts an asynchronous inquiry. Each found device is reported through the callback until discovery ends.
BTStatus SerialBT.discoverAsync(
std::function<void(const DiscoveryResult &)> callback,
uint32_t timeoutMs = 10000
);
The DiscoveryResult type is BluetoothSerial::DiscoveryResult.
discoverStop
BTStatus SerialBT.discoverStop();
Cancels an in-progress discovery and clears the async callback.
Security
enableSSP / disableSSP
void SerialBT.enableSSP(bool input = false, bool output = false);
void SerialBT.disableSSP();
enableSSP turns on Secure Simple Pairing. The input and output flags map to IO capability hints used during pairing (whether the device can display or accept user input).
setPin
Set a legacy PIN code for pairing (up to 16 characters; longer strings are truncated internally).
void SerialBT.setPin(const char *pin);
Bond management
std::vector<BTAddress> SerialBT.getBondedDevices();
BTStatus SerialBT.deleteBond(const BTAddress &address);
BTStatus SerialBT.deleteAllBonds();
getBondedDevices() returns all addresses currently stored in the controller bond list. The number of bonded devices is getBondedDevices().size().
Callbacks
onData
BTStatus SerialBT.onData(std::function<void(const uint8_t *, size_t)> callback);
Registers a callback invoked on the BT task whenever SPP data arrives (no source address). Prefer
onPeerData when multiple clients may be connected. Returns BTStatus::OK on success.
onConnect / onDisconnect
BTStatus SerialBT.onConnect(std::function<void(const BTAddress &)> callback);
BTStatus SerialBT.onDisconnect(std::function<void(const BTAddress &)> callback);
Per-peer connect and disconnect notifications. The BTAddress identifies which client joined or left.
onPeerData
BTStatus SerialBT.onPeerData(
std::function<void(const BTAddress &, const uint8_t *, size_t)> callback
);
Attributed RX callback: invoked with the source peer address and payload. Fired in addition to the
merged receive buffer used by read() / available().
SerialBT.onPeerData([](const BTAddress &addr, const uint8_t *data, size_t len) {
SerialBT.writeTo(addr, data, len); // echo to that peer only
});
onConfirmRequest
BTStatus SerialBT.onConfirmRequest(std::function<bool(uint32_t)> callback);
Registers a callback for SSP numeric-comparison pairing. The uint32_t argument is the numeric value to display to the user. The callback must return true to accept the pairing or false to reject it. Returns BTStatus::OK on success.
onAuthComplete
BTStatus SerialBT.onAuthComplete(std::function<void(bool)> callback);
Registers a callback invoked when authentication finishes. The bool argument is true on success. Returns BTStatus::OK on success.
Registration returns BTStatus::OK when the callback was stored, or an error such as BTStatus::InvalidState if Bluetooth is not in a valid state.
Info and state
getAddress
BTAddress SerialBT.getAddress() const;
Returns the local public Bluetooth address, or a zero address if not initialized.
operator bool
explicit operator bool() const;
Returns true when the Bluetooth stack has been initialized successfully (begin() returned BTStatus::OK). Because the conversion is explicit, implicit boolean conversions are not allowed; use static_cast<bool>(SerialBT) or test after begin().