CodexPad Arduino Lib 4.1.0
Loading...
Searching...
No Matches
scan_and_connect.ino

Demonstrates how to scan for and connect to a CodexPad device by matching specific button presses.

Demonstrates how to scan for and connect to a CodexPad device by matching specific button presses. This example shows the usage of the ScanAndConnect() function. The device will scan for nearby CodexPad devices and automatically connect to one where the operator is holding down the predefined combination of buttons (the button mask). The button mask is defined by the kExpectedButtonMask constant. You must physically press and hold the corresponding button(s) on the target CodexPad for the connection to succeed.

Warning
Important: When setting the button mask, do not use the Home button alone. Long-pressing the Home button will cause the gamepad to power off, interrupting the connection. If you must use the Home button, be sure to use it in combination with other buttons (e.g., Home + Cross).
See also
codex_pad::Client::ScanAndConnect
/**
* @~English
* @file scan_and_connect.ino
* @example scan_and_connect.ino
* @brief Demonstrates how to scan for and connect to a CodexPad device by matching specific button presses.
* @details This example shows the usage of the `ScanAndConnect()` function. The device will scan for nearby CodexPad devices
* and automatically connect to one where the operator is holding down the predefined combination of buttons (the
* *button mask*). The button mask is defined by the `kExpectedButtonMask` constant. You must physically press and hold
* the corresponding button(s) on the target CodexPad for the connection to succeed.
* @warning **Important:** When setting the button mask, **do not use the `Home` button alone**. Long-pressing the `Home` button
* will cause the gamepad to power off, interrupting the connection. If you must use the `Home` button, be sure to use it in
* combination with other buttons (e.g., `Home` + `Cross`).
* @see codex_pad::Client::ScanAndConnect
*/
/**
* @~Chinese
* @file scan_and_connect.ino
* @example scan_and_connect.ino
* @brief 演示如何通过匹配特定按键按压来扫描并连接 CodexPad 设备。
* @details 本示例展示了 `ScanAndConnect()` 函数的使用方法。设备将扫描附近的 CodexPad
* 设备,并自动连接到操作者正按住预定义按键组合(*按钮掩码*)的那一个。 按钮掩码由常量 `kExpectedButtonMask`
* 定义。您必须在目标手柄上物理按住对应的按键,连接才能成功。
* @warning **重要:** 设置按钮掩码时, 请勿单独使用 `Home` 键。长按 `Home` 键会导致手柄关机,从而中断连接。如确需使用 `Home`
* 键,请务必采用组合按键(如 `Home` + `Cross`)。.
* @see codex_pad::Client::ScanAndConnect
*/
#include <map>
#include "codex_pad.h"
#include "cyf.h"
#include "cyf/log.h"
/**
* IMPORTANT:
* This using directive is REQUIRED to directly access `Button` and `Axis`.
* Without it, you must write the fully qualified names:
* gamepad::input::Button::kUp
* gamepad::input::Axis::kLeftStickX
* Forgetting this line will cause compile errors when using Button or Axis.
*/
/**
* 重要:
* 必须使用该命名空间,否则无法直接访问 `Button` 和 `Axis`。
* 如果没有这一行,就必须写成完整限定名:
* gamepad::input::Button::kUp
* gamepad::input::Axis::kLeftStickX
* 忘记引入命名空间会导致编译失败。
*/
using namespace gamepad::input;
namespace {
// You can set a button mask to automatically connect when a target device is scanned and its button state matches this mask.
// For example, you can set it to connect only when a specific button is pressed, or when multiple specified buttons are pressed
// simultaneously on the device. 你可以设置一个按钮掩码,当扫描到目标设备并检测到其按键状态与该掩码匹配时,自动进行连接。
// 例如,可以设置为当设备上某个特定按键被按下,或多个指定按键被同时按下时才建立连接。
// 【Important Warning】DO NOT use `Button::kHome` (Home button) alone to set the button mask. Pressing and holding the Home
// button will trigger a device shutdown. If you need to use the Home button, it is recommended to use it in combination with
// other buttons (e.g., Home + Cross). 【重要警告】请勿单独使用 `Button::kHome` (Home键)
// 来设置按钮掩码。因为按住Home键会触发设备关机。如需使用Home键,建议采用组合按键方式(例如 Home + Cross)。
// Example 1: The button mask to match - Only the Start button
// 示例 1:需要匹配的按钮掩码 - 仅Start按钮
// constexpr auto kExpectedButtonMask = Button::kStart;
// Example 2: The button mask to match - Start and CrossA buttons
// 示例 2:需要匹配的按钮掩码 - Start 和 CrossA 按钮
constexpr auto kExpectedButtonMask = Button::kStart | Button::kCrossA;
// Example 3: The button mask to match - Start, CrossA, and SquareX buttons
// 示例 3:需要匹配的按钮掩码 - Start、CrossA 和 SquareX 按钮
// constexpr auto kExpectedButtonMask = Button::kStart | Button::kCrossA | Button::kSquareX;
const std::map<Button, std::string> kButtonNames{
{Button::kUp, "Up"},
{Button::kDown, "Down"},
{Button::kLeft, "Left"},
{Button::kRight, "Right"},
{Button::kSquareX, "Square(X)"},
{Button::kTriangleY, "Triangle(Y)"},
{Button::kCrossA, "Cross(A)"},
{Button::kCircleB, "Circle(B)"},
{Button::kL1, "L1"},
{Button::kR1, "R1"},
{Button::kL2, "L2"},
{Button::kR2, "R2"},
{Button::kL3, "L3"},
{Button::kR3, "R3"},
{Button::kSelect, "Select"},
{Button::kStart, "Start"},
{Button::kHome, "Home"},
};
codex_pad::Client g_codex_pad_client;
void Connect() {
CLOGI("Start to scan and connect, button mask: 0x%08" PRIX32, static_cast<uint32_t>(kExpectedButtonMask));
while (!g_codex_pad_client.ScanAndConnect(kExpectedButtonMask)) {
CLOGI("Retry to scan and connect, button mask: 0x%08" PRIX32, static_cast<uint32_t>(kExpectedButtonMask));
}
CLOGI("Remote device name: %s", g_codex_pad_client.remote_device_name().c_str());
CLOGI("Remote model number: %s", g_codex_pad_client.remote_model_number().c_str());
CLOGI("Remote firmware revision: %u.%u.%u", g_codex_pad_client.remote_firmware_version()[0],
g_codex_pad_client.remote_firmware_version()[1], g_codex_pad_client.remote_firmware_version()[2]);
if (const auto ble_client = g_codex_pad_client.ble_client(); ble_client != nullptr) {
CLOGI("Remote Bluetooth Device Address: %s", ble_client->getPeerAddress().toString().c_str());
} else {
CLOGI("Remote Bluetooth Device Address: unknown");
}
CLOGI("Connected");
}
void RssiMonitor() {
static uint64_t s_last_time = 0;
if (s_last_time == 0 || millis() - s_last_time > 1000) {
const int32_t rssi = g_codex_pad_client.rssi();
if (rssi != 0) {
if (rssi >= -65) {
CLOGI("rssi: %" PRId32 " dBm, | [#][#][#][#] | strong", rssi);
} else if (rssi >= -80) {
CLOGI("rssi: %" PRId32 " dBm, | [#][#][#][ ] | decent", rssi);
} else if (rssi >= -95) {
CLOGW("rssi: %" PRId32 " dBm, | [#][#][ ][ ] | weak", rssi);
} else {
CLOGW("rssi: %" PRId32 " dBm, | [#][ ][ ][ ] | critical", rssi);
}
} else {
CLOGI("rssi: unknown\n");
}
s_last_time = millis();
}
}
} // namespace
void setup() {
Serial.begin(115200);
CLOGI("Init");
// Set the TX power for the local BLE device (e.g., ESP32) in dBm.
// 9dBm is the maximum TX power for ESP32 in BLE mode, which helps improve signal coverage.
// NimBLETxPowerType::All applies this power level to both advertising and connection channels.
const int8_t tx_power = 9; // Local device TX power in dBm
g_codex_pad_client.Init(tx_power);
Connect();
}
void loop() {
// ==========================================================================
// 🔴 CRITICAL: Call Update() as frequently as possible in loop()
// ==========================================================================
// • Update() processes incoming Bluetooth packets from the CodexPad
// • Any delay(...) or long blocking code WILL cause:
// - Packet loss
// - Input lag
// - Unstable connection
//
// • For real-time control, call Update() every loop iteration
// without any blocking operations
//
// 🔴【重要】Update() 必须在 loop() 中尽可能高频调用
// • Update() 负责处理来自 CodexPad 的蓝牙数据包
// • 任何形式的 delay 或阻塞代码都会导致:
// - 数据丢失
// - 响应延迟
// - 连接不稳定
//
// • 实时控制应用中,必须每轮循环都调用 Update(),不可阻塞
// ==========================================================================
const gamepad::input::Tracker& it = g_codex_pad_client.Update();
// ==========================================================================
// Tracker: Gamepad Input Snapshot & Change Engine
// ==========================================================================
// • Returned by Update()
// • Maintains previous and current input snapshots
// • Enables edge detection and delta detection
//
// Tracker 由 Update() 返回
// 内部保存上一帧和当前帧的输入数据
// 支持边沿检测和差值检测
//
// 📚 https://codexpad.github.io/gamepad_input_arduino_lib/
// ==========================================================================
if (!g_codex_pad_client.is_connected()) {
CLOGW("Disconnected, start to reconnect");
Connect();
return;
}
RssiMonitor();
// ==========================================================================
// 🟢 Button State Change Detection (Edge-Based)
// ==========================================================================
// • pressed() → button was just pressed (released → pressed)
// • released() → button was just released (pressed → released)
// • holding() → button remains pressed across frames
//
// These APIs are *frame-differential* and rely on Update() frequency.
// Ideal for UI navigation, action triggers, and avoiding repeat firing.
//
// • pressed() → 按钮刚被按下(弹起 → 按下)
// • released() → 按钮刚被释放(按下 → 弹起)
// • holding() → 按钮在两帧之间持续按下
//
// 这些接口是“帧间差分”的,依赖于 Update() 的高频调用
// 非常适合 UI 导航、动作触发和防止长按连发
// ==========================================================================
static std::map<Button, uint64_t> s_button_last_time;
for (const auto& [button, name] : kButtonNames) {
if (it.pressed(button)) { // button was just pressed
CLOGI("Button mask: 0x%08" PRIX32 ", button %s: pressed", it.raw().buttons, name.c_str());
s_button_last_time[button] = millis();
} else if (it.released(button)) { // button was just released
CLOGI("Button mask: 0x%08" PRIX32 ", button %s: released", it.raw().buttons, name.c_str());
s_button_last_time[button] = millis();
} else if (it.holding(button)) { // button remains pressed
if (s_button_last_time.find(button) == s_button_last_time.end() || s_button_last_time[button] == 0 ||
millis() - s_button_last_time[button] > 100) {
CLOGI("Button mask: 0x%08" PRIX32 ", button %s: holding", it.raw().buttons, name.c_str());
s_button_last_time[button] = millis();
}
}
}
// ==========================================================================
// 🟢 Joystick Axis Change Detection (Threshold-Based Filtering)
// ==========================================================================
// • AxisChanged() detects significant changes between frames
// • Uses a threshold to filter out noise and minor jitter
// • Only reports movement when change ≥ threshold
//
// • AxisChanged() 用于检测摇杆轴值的有效变化
// • 使用阈值过滤微小抖动和噪声
// • 只有当变化幅度 ≥ 阈值时才视为有效移动
// ==========================================================================
constexpr uint8_t kAxisValueChangeThreshold = 5;
if (it.AxisChanged(Axis::kLeftStickX, kAxisValueChangeThreshold) ||
it.AxisChanged(Axis::kLeftStickY, kAxisValueChangeThreshold) ||
it.AxisChanged(Axis::kRightStickX, kAxisValueChangeThreshold) ||
it.AxisChanged(Axis::kRightStickY, kAxisValueChangeThreshold)) {
CLOGI("L(X: %3" PRIu8 ", Y:%3" PRIu8 "), R(X: %3" PRIu8 ", Y: %3" PRIu8 ")", it[Axis::kLeftStickX], it[Axis::kLeftStickY],
it[Axis::kRightStickX], it[Axis::kRightStickY]);
}
}
Client main class.
Definition client.h:25
const std::string & remote_device_name() const noexcept
Get model number of the CodexPad.
Definition client.h:176
const std::array< uint8_t, 3 > & remote_firmware_version() const noexcept
Get firmware version of the CodexPad.
Definition client.h:200
NimBLEClient * ble_client() const noexcept
Get the BLE client object.
Definition client.h:241
bool ScanAndConnect(gamepad::input::Button buttons) noexcept
Scans for nearby CodexPad devices and automatically connects to a device whose button state matches t...
Definition client.cpp:59
const std::string & remote_model_number() const noexcept
Get model number of the CodexPad.
Definition client.h:188
int32_t rssi() const noexcept
Get the RSSI of the CodexPad.
Definition client.cpp:230