Examples

The examples/ directory contains three sample applications:

  1. QuickStart: Minimal serial output sketch for any ESP32 board with no display dependencies.
  2. M5Core2_Basic: Practical touchscreen UI template for M5Stack Core2 showing non-blocking pairing, an NVS saved keyboard list, and live text typing.
  3. M5Core2_KeyInspector: Hardware diagnostic and keymap verification tool for M5Stack Core2 with live HID Usage inspection, runtime US and JIS switching, raw packet logging, and unmapped key tracking.

Build and flash the examples

Option 1: Clone the repository

Clone this repository to build and flash any example without copying files. Select an environment (quickstart, m5core2_basic, or m5core2_inspector) from the PlatformIO status bar in VS Code, or run one of the following commands in your terminal:

git clone https://github.com/tinyalg/BleKbdHost.git
cd BleKbdHost

# Minimal serial example (default board: esp32dev)
pio run -e quickstart -t upload -t monitor

# M5Stack Core2 touchscreen UI example
pio run -e m5core2_basic -t upload

# M5Stack Core2 keymap and raw report inspector
pio run -e m5core2_inspector -t upload

Board selection: The quickstart environment targets generic esp32dev boards. On M5Stack Core2, run pio run -e m5core2_quickstart -t upload -t monitor instead so M5Unified initializes power management and mutes speaker noise, or try the touchscreen apps (m5core2_basic and m5core2_inspector).

Option 2: Copy into your own PlatformIO project

To try an example inside a separate PlatformIO project, add the required libraries to lib_deps in your platformio.ini and copy main.cpp from the corresponding examples/ folder into your project's src/ directory.

For QuickStart on a generic ESP32 board:

[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 115200
lib_deps =
    h2zero/NimBLE-Arduino@^2.5.2
    https://github.com/tinyalg/BleKbdHost.git

For M5Core2_Basic and M5Core2_KeyInspector on M5Stack Core2:

[env:m5stack-core2]
platform = espressif32
board = m5stack-core2
framework = arduino
monitor_speed = 115200
lib_deps =
    m5stack/M5Unified
    h2zero/NimBLE-Arduino@^2.5.2
    https://github.com/tinyalg/BleKbdHost.git

1. QuickStart

Source: examples/QuickStart/main.cpp

A minimal sketch that prints saved keyboards, connection state changes, and typed ASCII characters to the Serial Monitor at 115200 bps.

  • Startup: Lists all saved keyboards from NVS (getPairedCount() and getPairedDevice()).
  • First boot (no saved bond): Opens a 30-second pairing scan (startPairing(30000)). Put your BLE keyboard into pairing mode to connect.
  • Subsequent boots: Enters State::WaitingReconnect and reconnects automatically whenever a bonded keyboard wakes up.
  • Pair another keyboard or reset bonds: Send p or u from the Serial Monitor at any time (no re-flashing required).

Serial commands

Send single-character commands from the Serial Monitor (115200 bps):

Command Action
p Starts a 30-second pairing scan (startPairing(30000)), disconnecting any active session, or cancels an active scan (cancelPairing()).
u Calls requestUnpair() to disconnect and erase all saved BLE bonds and cached NVS device names.

JIS keyboard users: Uncomment keyboard.setLayout(BleKbdHost::Layout::JIS); in setup() before calling keyboard.begin().


2. M5Core2_Basic

Source: examples/M5Core2_Basic/main.cpp

A clean reference implementation demonstrating how to integrate BleKbdHost into an interactive GUI loop without blocking touch input or display rendering.

Screen layout

The application divides the 320x240 screen into three independent regions:

  • Top status badge (y = 0..26): Displays the current BleKbdHost::State, pairing countdown timer (getPairingRemainingSec()), or connected keyboard name (getDeviceName()). Also acts as a touch button.
  • Center typing area (y = 30..166): Hardware-accelerated vertical scrolling text region (setScrollRect) that prints decoded ASCII characters (ev.ascii) as you type.
  • Saved keyboards panel (y = 168..240): Lists up to three bonded keyboards retrieved with getPairedCount() and getPairedDevice(), highlighting the active device with a green asterisk (*).

Status badge colors

State Badge color Label
State::Idle Dark grey KB: NONE [TAP TO PAIR]
State::WaitingReconnect Navy KB: STANDBY [TAP:NEW]
State::PairingScan Orange PAIRING (30s) [TAP:STOP]
State::Connecting Orange KB: CONNECTING...
State::Connected Dark green KB: <Device Name>

Controls

Input Action
Tap top status bar (y < 30) Starts a 30-second pairing scan (startPairing(30000)) when disconnected, or cancels an active scan (cancelPairing()).
Hold BtnC (1.5 seconds) Calls requestUnpair() to disconnect and erase all saved BLE bonds and cached NVS device names.

JIS keyboard users: Uncomment keyboard.setLayout(BleKbdHost::Layout::JIS); in setup() before calling keyboard.begin().


3. M5Core2_KeyInspector

Source: examples/M5Core2_KeyInspector/main.cpp

A diagnostic workbench designed to verify every key on US and JIS keyboards—including Shift layers, modifiers, function keys, JIS conversion keys, and 16-bit Consumer Control media keys—and to inspect unknown BLE HID keyboards.

Screen layout

  • Top status bar (y = 0..26): Touch-activated connection status bar and countdown timer.
  • Inspector panel (y = 28..96):
  • Shows the active layout (US or JIS).
  • Displays decoded output in green ('a' (0x61)), the SpecialKey name in cyan ([Enter], [VolUp], [Muhenkan]), or (unmapped) in orange.
  • Displays the raw hexadecimal HID Usage ID (Code:0x04 or Cons:0x00E9), active modifier flags (S = Shift, C = Ctrl, A = Alt, G = GUI), and mapped SpecialKey.
  • Typing preview area (y = 100..240): Scrolling text preview for printable characters.

Controls

Input Action
Tap top status bar (y < 28) Starts a 30-second pairing scan or cancels an active scan.
Tap BtnA Toggles keymap decoding at runtime between Layout::US and Layout::JIS.
Tap BtnB Clears the typing area and prints a summary of all unique unmapped keycodes and consumer codes to the Serial Monitor.
Hold BtnC (1.5 seconds) Calls requestUnpair() to clear all saved BLE bonds and NVS names.

Serial Monitor output

M5Core2_KeyInspector registers setRawReportCallback() to log every incoming GATT notification alongside the decoded KeyEvent row at 115200 bps:

=== BleKbdHost Full Key Verification ===
Layout | Source      | Mod    | Special        | ASCII
[RAW] handle=0x0015 len= 8 data: 02 00 1F 00 00 00 00 00
JIS    | Key :0x1F   | Mod:02 | Sp:None        | 0x22 (")
[RAW] handle=0x0015 len= 8 data: 02 00 00 00 00 00 00 00
[RAW] handle=0x0019 len= 2 data: E9 00
JIS    | Cons:0x00E9 | Mod:-- | Sp:VolUp       | --
[RAW] handle=0x0019 len= 2 data: 00 00

If a key produces neither an ASCII character nor a known SpecialKey, the inspector flags it with <--- [UNMAPPED KEY!] or <--- [UNMAPPED CONSUMER!] and records its code so you can review all missing keys at once by pressing BtnB.