CodexPad Arduino 库 5.0.0
载入中...
搜索中...
未找到
button_mask_connection.ino
浏览该文件的文档.
1/**
2 * @~English
3 * @file button_mask_connection.ino
4 * @example button_mask_connection.ino
5 * @brief Demonstrates how to scan for and connect to a CodexPad device by matching specific button presses.
6 * @details This example shows the usage of the `Connect()` function. The device will scan for nearby CodexPad devices
7 * and automatically connect to one where the operator is holding down the predefined combination of buttons (the
8 * *button mask*). The button mask is defined by the `kExpectedButtonMask` constant. You must physically press and hold
9 * the corresponding button(s) on the target CodexPad for the connection to succeed.
10 * @warning **Important:** When setting the button mask, **do not use the `Home` button alone**. Long-pressing the `Home` button
11 * will cause the gamepad to power off, interrupting the connection. If you must use the `Home` button, be sure to use it in
12 * combination with other buttons (e.g., `Home` + `Cross`).
13 * @see codex_pad::Client::Connect
14 */
15/**
16 * @~Chinese
17 * @file button_mask_connection.ino
18 * @example button_mask_connection.ino
19 * @brief 演示如何通过匹配特定按键按压来扫描并连接 CodexPad 设备。
20 * @details 本示例展示了 `Connect()` 函数的使用方法。设备将扫描附近的 CodexPad
21 * 设备,并自动连接到操作者正按住预定义按键组合(*按钮掩码*)的那一个。 按钮掩码由常量 `kExpectedButtonMask`
22 * 定义。您必须在目标手柄上物理按住对应的按键,连接才能成功。
23 * @warning **重要:** 设置按钮掩码时, 请勿单独使用 `Home` 键。长按 `Home` 键会导致手柄关机,从而中断连接。如确需使用 `Home`
24 * 键,请务必采用组合按键(如 `Home` + `Cross`)。.
25 * @see codex_pad::Client::Connect
26 */
27
28#include <map>
29
30#include "codex_pad.h"
31#include "cyf.h"
32#include "cyf/log.h"
33
34/**
35 * IMPORTANT:
36 * This using directive is REQUIRED to directly access `Button` and `Axis`.
37 * Without it, you must write the fully qualified names:
38 * gamepad::input::Button::kUp
39 * gamepad::input::Axis::kLeftStickX
40 * Forgetting this line will cause compile errors when using Button or Axis.
41 */
42/**
43 * 重要:
44 * 必须使用该命名空间,否则无法直接访问 `Button` 和 `Axis`。
45 * 如果没有这一行,就必须写成完整限定名:
46 * gamepad::input::Button::kUp
47 * gamepad::input::Axis::kLeftStickX
48 * 忘记引入命名空间会导致编译失败。
49 */
50using namespace gamepad::input;
51
52namespace {
53// You can set a button mask to automatically connect when a target device is scanned and its button state matches this mask.
54// For example, you can set it to connect only when a specific button is pressed, or when multiple specified buttons are pressed
55// simultaneously on the device. 你可以设置一个按钮掩码,当扫描到目标设备并检测到其按键状态与该掩码匹配时,自动进行连接。
56// 例如,可以设置为当设备上某个特定按键被按下,或多个指定按键被同时按下时才建立连接。
57
58// 【Important Warning】DO NOT use `Button::kHome` (Home button) alone to set the button mask. Pressing and holding the Home
59// button will trigger a device shutdown. If you need to use the Home button, it is recommended to use it in combination with
60// other buttons (e.g., Home + Cross). 【重要警告】请勿单独使用 `Button::kHome` (Home键)
61// 来设置按钮掩码。因为按住Home键会触发设备关机。如需使用Home键,建议采用组合按键方式(例如 Home + Cross)。
62
63// Example 1: The button mask to match - Only the Start button
64// 示例 1:需要匹配的按钮掩码 - 仅Start按钮
65// constexpr auto kExpectedButtonMask = Button::kStart;
66
67// Example 2: The button mask to match - Start and CrossA buttons
68// 示例 2:需要匹配的按钮掩码 - Start 和 CrossA 按钮
69constexpr auto kExpectedButtonMask = Button::kStart | Button::kCrossA;
70
71// Example 3: The button mask to match - Start, CrossA, and SquareX buttons
72// 示例 3:需要匹配的按钮掩码 - Start、CrossA 和 SquareX 按钮
73// constexpr auto kExpectedButtonMask = Button::kStart | Button::kCrossA | Button::kSquareX;
74
75const std::map<Button, std::string> kButtonNames{
76 {Button::kUp, "Up"},
77 {Button::kDown, "Down"},
78 {Button::kLeft, "Left"},
79 {Button::kRight, "Right"},
80 {Button::kSquareX, "Square(X)"},
81 {Button::kTriangleY, "Triangle(Y)"},
82 {Button::kCrossA, "Cross(A)"},
83 {Button::kCircleB, "Circle(B)"},
84 {Button::kL1, "L1"},
85 {Button::kR1, "R1"},
86 {Button::kL2, "L2"},
87 {Button::kR2, "R2"},
88 {Button::kL3, "L3"},
89 {Button::kR3, "R3"},
90 {Button::kSelect, "Select"},
91 {Button::kStart, "Start"},
92 {Button::kHome, "Home"},
93};
94
95codex_pad::Client g_codex_pad_client;
96
97void Connect() {
98 CLOGI("Start to scan and connect, button mask: 0x%08" PRIX32, static_cast<uint32_t>(kExpectedButtonMask));
99
100 while (!g_codex_pad_client.Connect(kExpectedButtonMask)) {
101 CLOGI("Retry to scan and connect, button mask: 0x%08" PRIX32, static_cast<uint32_t>(kExpectedButtonMask));
102 }
103
104 CLOGI("Remote device name: %s", g_codex_pad_client.remote_device_name().c_str());
105 CLOGI("Remote model number: %s", g_codex_pad_client.remote_model_number().c_str());
106 CLOGI("Remote firmware revision: %u.%u.%u", g_codex_pad_client.remote_firmware_version()[0],
107 g_codex_pad_client.remote_firmware_version()[1], g_codex_pad_client.remote_firmware_version()[2]);
108
109 if (const auto ble_client = g_codex_pad_client.ble_client(); ble_client != nullptr) {
110 CLOGI("Remote Bluetooth Device Address: %s", ble_client->getPeerAddress().toString().c_str());
111 } else {
112 CLOGI("Remote Bluetooth Device Address: unknown");
113 }
114
115 CLOGI("Connected");
116}
117
118void RssiMonitor() {
119 static uint64_t s_last_time = 0;
120
121 if (s_last_time == 0 || millis() - s_last_time > 1000) {
122 const int32_t rssi = g_codex_pad_client.rssi();
123 if (rssi != 0) {
124 if (rssi >= -65) {
125 CLOGI("rssi: %" PRId32 " dBm, | [#][#][#][#] | strong", rssi);
126 } else if (rssi >= -80) {
127 CLOGI("rssi: %" PRId32 " dBm, | [#][#][#][ ] | decent", rssi);
128 } else if (rssi >= -95) {
129 CLOGW("rssi: %" PRId32 " dBm, | [#][#][ ][ ] | weak", rssi);
130 } else {
131 CLOGW("rssi: %" PRId32 " dBm, | [#][ ][ ][ ] | critical", rssi);
132 }
133 } else {
134 CLOGI("rssi: unknown\n");
135 }
136
137 s_last_time = millis();
138 }
139}
140} // namespace
141
142void setup() {
143 Serial.begin(115200);
144
145 CLOGI("Init");
146 g_codex_pad_client.Init();
147
148 Connect();
149}
150
151void loop() {
152 // ==========================================================================
153 // 🔴 CRITICAL: Call Update() as frequently as possible in loop()
154 // ==========================================================================
155 // • Update() processes incoming Bluetooth packets from the CodexPad
156 // • Any delay(...) or long blocking code WILL cause:
157 // - Packet loss
158 // - Input lag
159 // - Unstable connection
160 //
161 // • For real-time control, call Update() every loop iteration
162 // without any blocking operations
163 //
164 // 🔴【重要】Update() 必须在 loop() 中尽可能高频调用
165 // • Update() 负责处理来自 CodexPad 的蓝牙数据包
166 // • 任何形式的 delay 或阻塞代码都会导致:
167 // - 数据丢失
168 // - 响应延迟
169 // - 连接不稳定
170 //
171 // • 实时控制应用中,必须每轮循环都调用 Update(),不可阻塞
172 // ==========================================================================
173 const gamepad::input::Tracker& it = g_codex_pad_client.Update();
174 // ==========================================================================
175 // Tracker: Gamepad Input Snapshot & Change Engine
176 // ==========================================================================
177 // • Returned by Update()
178 // • Maintains previous and current input snapshots
179 // • Enables edge detection and delta detection
180 //
181 // Tracker 由 Update() 返回
182 // 内部保存上一帧和当前帧的输入数据
183 // 支持边沿检测和差值检测
184 //
185 // 📚 https://codexpad.github.io/gamepad_input_arduino_lib/
186 // ==========================================================================
187
188 if (!g_codex_pad_client.is_connected()) {
189 CLOGW("Disconnected, start to reconnect");
190 Connect();
191 return;
192 }
193
194 RssiMonitor();
195
196 // ==========================================================================
197 // 🟢 Button State Change Detection (Edge-Based)
198 // ==========================================================================
199 // • pressed() → button was just pressed (released → pressed)
200 // • released() → button was just released (pressed → released)
201 // • holding() → button remains pressed across frames
202 //
203 // These APIs are *frame-differential* and rely on Update() frequency.
204 // Ideal for UI navigation, action triggers, and avoiding repeat firing.
205 //
206 // • pressed() → 按钮刚被按下(弹起 → 按下)
207 // • released() → 按钮刚被释放(按下 → 弹起)
208 // • holding() → 按钮在两帧之间持续按下
209 //
210 // 这些接口是“帧间差分”的,依赖于 Update() 的高频调用
211 // 非常适合 UI 导航、动作触发和防止长按连发
212 // ==========================================================================
213 static std::map<Button, uint64_t> s_button_last_time;
214
215 for (const auto& [button, name] : kButtonNames) {
216 if (it.pressed(button)) { // button was just pressed
217 CLOGI("Button mask: 0x%08" PRIX32 ", button %s: pressed", it.button_mask(), name.c_str());
218 s_button_last_time[button] = millis();
219 } else if (it.released(button)) { // button was just released
220 CLOGI("Button mask: 0x%08" PRIX32 ", button %s: released", it.button_mask(), name.c_str());
221 s_button_last_time[button] = millis();
222 } else if (it.holding(button)) { // button remains pressed
223 if (s_button_last_time.find(button) == s_button_last_time.end() || s_button_last_time[button] == 0 ||
224 millis() - s_button_last_time[button] > 100) {
225 CLOGI("Button mask: 0x%08" PRIX32 ", button %s: holding", it.button_mask(), name.c_str());
226 s_button_last_time[button] = millis();
227 }
228 }
229 }
230
231 // ==========================================================================
232 // 🟢 Joystick Axis Change Detection (Threshold-Based Filtering)
233 // ==========================================================================
234 // • AxisChanged() detects significant changes between frames
235 // • Uses a threshold to filter out noise and minor jitter
236 // • Only reports movement when change ≥ threshold
237 //
238 // • AxisChanged() 用于检测摇杆轴值的有效变化
239 // • 使用阈值过滤微小抖动和噪声
240 // • 只有当变化幅度 ≥ 阈值时才视为有效移动
241 // ==========================================================================
242 constexpr uint8_t kAxisValueChangeThreshold = 5;
243
244 if (it.AxisChanged(Axis::kLeftStickX, kAxisValueChangeThreshold) ||
245 it.AxisChanged(Axis::kLeftStickY, kAxisValueChangeThreshold) ||
246 it.AxisChanged(Axis::kRightStickX, kAxisValueChangeThreshold) ||
247 it.AxisChanged(Axis::kRightStickY, kAxisValueChangeThreshold)) {
248 CLOGI("L(X: %3" PRIu8 ", Y:%3" PRIu8 "), R(X: %3" PRIu8 ", Y: %3" PRIu8 ")", it[Axis::kLeftStickX], it[Axis::kLeftStickY],
249 it[Axis::kRightStickX], it[Axis::kRightStickY]);
250 }
251}
Client主类
const gamepad::input::Tracker & Update() noexcept
更新,需要在Loop中不断调用
const std::string & remote_device_name() const noexcept
获取CodexPad的型号
const std::array< uint8_t, 3 > & remote_firmware_version() const noexcept
获取CodexPad的固件版本
bool is_connected() const noexcept
是否连接
NimBLEClient * ble_client() const noexcept
获取 BLE 客户端对象
void Init() noexcept
初始化
const std::string & remote_model_number() const noexcept
获取CodexPad的型号
int32_t rssi() const noexcept
获取已连接 CodexPad 的 RSSI(接收信号强度指示)。
bool Connect(const std::string &address, uint32_t timeout_ms=5000) noexcept
连接