Get started
Requirements
- Hardware: ESP32-based board (such as ESP32 or M5Stack Core2)
- Framework: Arduino for ESP32
- Dependencies:
h2zero/NimBLE-Arduinov2.5.2 or later
Installation
PlatformIO (recommended)
Add NimBLE-Arduino and the BleKbdHost repository to lib_deps in your platformio.ini file:
lib_deps =
h2zero/NimBLE-Arduino@^2.5.2
https://github.com/tinyalg/BleKbdHost.git
Quick start
You can find this minimal serial sketch in examples/QuickStart/main.cpp.
- Build and flash the sketch, and then open the Serial Monitor (
115200bps). - After a reset with no saved bond, the ESP32 starts a 30-second pairing scan. Put your Bluetooth keyboard into pairing mode to connect.
- Once
[State] Connectedappears, type on your keyboard to print characters in the Serial Monitor. - Reboot the ESP32, and then press any key on your keyboard to wake it up and reconnect without re-pairing. To switch keyboards, send
pto start a new pairing scan oruto clear saved bonds.
#include <Arduino.h>
#include "BleKbdHost.h"
BleKbdHost keyboard;
const char* errorToString(BleKbdHost::Error err) {
switch (err) {
case BleKbdHost::Error::PairingTimeout: return "PairingTimeout";
case BleKbdHost::Error::ConnectFailed: return "ConnectFailed";
case BleKbdHost::Error::AuthFailed: return "AuthFailed";
case BleKbdHost::Error::NoHidService: return "NoHidService";
case BleKbdHost::Error::SubscribeFailed: return "SubscribeFailed";
default: return nullptr;
}
}
void printPairedDevices() {
int count = keyboard.getPairedCount();
Serial.printf("Saved keyboards (%d):\n", count);
if (count == 0) {
Serial.println(" (none)");
return;
}
for (int i = 0; i < count; i++) {
BleKbdHost::PairedDevice dev;
if (keyboard.getPairedDevice(i, dev)) {
const char* name = (dev.name[0] != '\0') ? dev.name : "(unknown)";
Serial.printf(" %s %d: %s [%s]\n",
dev.connected ? "*" : "-",
i + 1,
name,
dev.address);
}
}
}
void printState(BleKbdHost::State state) {
switch (state) {
case BleKbdHost::State::Idle:
Serial.println("[State] Idle (Send 'p' to pair)");
break;
case BleKbdHost::State::WaitingReconnect:
Serial.println("[State] WaitingReconnect (Send 'p' to pair new, 'u' to unpair)");
break;
case BleKbdHost::State::PairingScan:
Serial.printf("[State] PairingScan (%lus)...\n",
(unsigned long)keyboard.getPairingRemainingSec());
break;
case BleKbdHost::State::Connecting:
Serial.println("[State] Connecting...");
break;
case BleKbdHost::State::Connected:
Serial.printf("[State] Connected to: %s\n", keyboard.getDeviceName());
break;
}
const char* errStr = errorToString(keyboard.getLastError());
if (errStr != nullptr) {
Serial.printf(" [LastError] %s\n", errStr);
}
}
void setup() {
Serial.begin(115200);
delay(200);
Serial.println("\n=== BleKbdHost QuickStart ===");
// Optional: Use Japanese (JIS) layout instead of default US layout
// keyboard.setLayout(BleKbdHost::Layout::JIS);
keyboard.begin("ESP32-BleHost");
printPairedDevices();
// If no keyboard has been paired yet, open a 30-second pairing window
if (!keyboard.hasSavedBond()) {
Serial.println("Starting 30-second pairing scan...");
keyboard.startPairing(30000);
}
}
void loop() {
// Serial commands: 'p' to start/cancel pairing, 'u' to unpair saved bonds
while (Serial.available() > 0) {
char cmd = (char)Serial.read();
if (cmd == 'p' || cmd == 'P') {
if (keyboard.getState() == BleKbdHost::State::PairingScan) {
keyboard.cancelPairing();
} else {
keyboard.startPairing(30000);
}
} else if (cmd == 'u' || cmd == 'U') {
Serial.println("Unpairing all saved keyboards...");
keyboard.requestUnpair();
}
}
BleKbdHost::State state;
if (keyboard.pollStateChange(state)) {
printState(state);
if (state == BleKbdHost::State::Connected || state == BleKbdHost::State::Idle) {
printPairedDevices();
}
}
BleKbdHost::KeyEvent ev;
while (keyboard.pollEvent(ev)) {
if (ev.ascii != 0) {
Serial.print(ev.ascii);
}
}
delay(10);
}
Connection and pairing lifecycle
BleKbdHost manages BLE connections asynchronously through five states (BleKbdHost::State):
Idle: The host enters this state afterbegin()when no saved bonds exist in flash, or after you callrequestUnpair(). Scanning stops in this state.PairingScan: Starts when you callstartPairing(timeoutMs). The host actively scans for peripherals advertising the BLE HID Service (0x1812). If the timeout expires or you callcancelPairing(), the host returns toWaitingReconnect(if saved bonds exist) orIdle(if none exist).Connecting: Starts when the scan finds a target keyboard. The host verifies the HID service, establishesJust Worksencryption and bonding, reads the Report Map, switches to Report Mode, subscribes to input reports, and then caches the resolved device name in NVS. If subscription fails during a new pairing, the temporary bond is automatically rolled back.Connected: Ready to receive keystrokes and Consumer Control events throughpollEvent()orreadChar().WaitingReconnect: The host enters this state at boot if saved bonds exist, or whenever a bonded keyboard disconnects (such as during power-saving sleep). It watches for bonded addresses—including RPA-resolved addresses—and reconnects without re-pairing when you press a key to wake the keyboard.
stateDiagram-v2
[*] --> Idle: No bonds
[*] --> WaitingReconnect: Saved bonds
Idle --> PairingScan: startPairing()
PairingScan --> Idle: Timeout / cancel (no bonds)
WaitingReconnect --> PairingScan: startPairing()
PairingScan --> WaitingReconnect: Timeout / cancel (saved bonds)
PairingScan --> Connecting: HID keyboard found
Connecting --> PairingScan: Failed (time remaining)
WaitingReconnect --> Connecting: Bonded device wakes
Connecting --> Connected: Paired and subscribed
Connected --> WaitingReconnect: Disconnected / sleep
Additional transitions (omitted from diagram for clarity):
- Calling
requestUnpair()from any state clears all saved bonds and returns immediately toIdle.- Calling
startPairing()whileConnecteddisconnects the current keyboard and entersPairingScan.- If a connection attempt in
Connectingfails on reconnect or after the pairing timer has already expired, the host returns directly toWaitingReconnect(if saved bonds exist) orIdle(if none exist).
Share NimBLE with other libraries
By default, keyboard.begin("ESP32-BleHost", true) initializes the NimBLE stack and configures Just Works bonding security parameters.
If your application calls NimBLEDevice::init() beforehand, pass initBleStack = false and configure bonding and ID key distribution in your own initialization code:
NimBLEDevice::init("MyCustomApp");
NimBLEDevice::setSecurityAuth(true, false, true);
NimBLEDevice::setSecurityIOCap(BLE_HS_IO_NO_INPUT_OUTPUT);
NimBLEDevice::setSecurityInitKey(BLE_SM_PAIR_KEY_DIST_ENC | BLE_SM_PAIR_KEY_DIST_ID);
NimBLEDevice::setSecurityRespKey(BLE_SM_PAIR_KEY_DIST_ENC | BLE_SM_PAIR_KEY_DIST_ID);
keyboard.begin("MyCustomApp", false);
Included examples
The examples/ directory provides three sketches:
examples/QuickStart: Minimal serial monitor sketch for any ESP32 board with no display dependencies.examples/M5Core2_Basic: Touchscreen UI demonstration for M5Stack Core2 with connection state badges, pairing and unpairing controls, a saved device list from NVS, and a live text input area.examples/M5Core2_KeyInspector: Diagnostic utility for M5Stack Core2 that logs raw HID report packets alongside decodedKeyEventfields, with runtimeUSandJISlayout switching.
See Examples for setup details, screen layouts, and controls.