CodexPad Arduino Lib 4.2.0
Loading...
Searching...
No Matches
inputs_detection.ino
Go to the documentation of this file.
1/**
2 * @~English
3 * @file inputs_detection.ino
4 * @example inputs_detection.ino
5 * @brief Demonstrates how to detect real-time button states and joystick movements of a connected CodexPad.
6 * @details This example establishes a connection to a specific CodexPad device (by Bluetooth Device Address) and continuously
7 * monitors all user inputs. It showcases the detection of three distinct button states: **pressed** (momentary press),
8 * **released** (momentary release), and
9 * **holding** (sustained press). It also monitors the analog joystick axes and prints their values when a significant
10 * change beyond a set threshold is detected, filtering out minor jitter.
11 * @note The `Update()` method must be called as frequently as possible within the main loop without delays to ensure
12 * real-time responsiveness and prevent data packet loss.
13 * @see codex_pad::Client::Update
14 */
15/**
16 * @~Chinese
17 * @file inputs_detection.ino
18 * @example inputs_detection.ino
19 * @brief 演示如何检测已连接的 CodexPad 设备的实时按钮状态与摇杆移动。
20 * @details 本示例通过Bluetooth Device Address连接到指定的 CodexPad 设备,并持续监控所有用户输入。
21 * 它展示了三种不同的按钮状态检测: **按下** (瞬间按下)、 **释放** (瞬间释放)和 **持续按住** 。
22 * 同时,它监控模拟摇杆轴,当检测到超过设定阈值的显著变化时打印其值,从而过滤微小抖动。
23 * @note 必须在主循环中尽可能频繁地调用 `Update()` 方法,且不得添加延时,以确保实时响应性并防止数据包丢失。
24 * @see codex_pad::Client::Update
25 */
26
27#include <map>
28#include <string>
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// Replace with your CodexPad device's Bluetooth device address
54// 替换为你的 CodexPad 的 Bluetooth device address
55const std::string kBluetoothDeviceAddress = "E4:66:E5:A2:17:06";
56
57const std::map<Button, std::string> kButtonNames{
58 {Button::kUp, "Up"},
59 {Button::kDown, "Down"},
60 {Button::kLeft, "Left"},
61 {Button::kRight, "Right"},
62 {Button::kSquareX, "Square(X)"},
63 {Button::kTriangleY, "Triangle(Y)"},
64 {Button::kCrossA, "Cross(A)"},
65 {Button::kCircleB, "Circle(B)"},
66 {Button::kL1, "L1"},
67 {Button::kR1, "R1"},
68 {Button::kL2, "L2"},
69 {Button::kR2, "R2"},
70 {Button::kL3, "L3"},
71 {Button::kR3, "R3"},
72 {Button::kSelect, "Select"},
73 {Button::kStart, "Start"},
74 {Button::kHome, "Home"},
75};
76
77codex_pad::Client g_codex_pad_client;
78
79void Connect() {
80 CLOGI("Start to connect %s", kBluetoothDeviceAddress.c_str());
81 // Connect to the CodexPad with specified Bluetooth device address
82 // 连接到指定蓝牙设备地址的手柄
83 while (!g_codex_pad_client.Connect(kBluetoothDeviceAddress, 5000)) {
84 CLOGI("Retry to connect %s", kBluetoothDeviceAddress.c_str());
85 }
86
87 CLOGI("Remote device name: %s", g_codex_pad_client.remote_device_name().c_str());
88 CLOGI("Remote model number: %s", g_codex_pad_client.remote_model_number().c_str());
89 CLOGI("Remote firmware revision: %u.%u.%u", g_codex_pad_client.remote_firmware_version()[0],
90 g_codex_pad_client.remote_firmware_version()[1], g_codex_pad_client.remote_firmware_version()[2]);
91
92 if (const auto ble_client = g_codex_pad_client.ble_client(); ble_client != nullptr) {
93 CLOGI("Remote Bluetooth Device Address: %s", ble_client->getPeerAddress().toString().c_str());
94 } else {
95 CLOGI("Remote Bluetooth Device Address: unknown");
96 }
97
98 CLOGI("Connected");
99}
100
101void RssiMonitor() {
102 static uint64_t s_last_time = 0;
103
104 if (s_last_time == 0 || millis() - s_last_time > 1000) {
105 const int32_t rssi = g_codex_pad_client.rssi();
106 if (rssi != 0) {
107 if (rssi >= -65) {
108 CLOGI("rssi: %" PRId32 " dBm, | [#][#][#][#] | strong", rssi);
109 } else if (rssi >= -80) {
110 CLOGI("rssi: %" PRId32 " dBm, | [#][#][#][ ] | decent", rssi);
111 } else if (rssi >= -95) {
112 CLOGW("rssi: %" PRId32 " dBm, | [#][#][ ][ ] | weak", rssi);
113 } else {
114 CLOGW("rssi: %" PRId32 " dBm, | [#][ ][ ][ ] | critical", rssi);
115 }
116 } else {
117 CLOGI("rssi: unknown\n");
118 }
119
120 s_last_time = millis();
121 }
122}
123} // namespace
124
125void setup() {
126 Serial.begin(115200);
127
128 CLOGI("Init");
129 g_codex_pad_client.Init();
130
131 // Set the TX power for the local BLE device (e.g., ESP32) in dBm.
132 // 9dBm is the maximum TX power for ESP32 in BLE mode, which helps improve signal coverage.
133 // NimBLETxPowerType::All applies this power level to both advertising and connection channels.
134 const int8_t tx_power = 9; // Local device TX power in dBm
135 g_codex_pad_client.Init(tx_power);
136
137 Connect();
138}
139
140void loop() {
141 // ==========================================================================
142 // 🔴 CRITICAL: Call Update() as frequently as possible in loop()
143 // ==========================================================================
144 // • Update() processes incoming Bluetooth packets from the CodexPad
145 // • Any delay(...) or long blocking code WILL cause:
146 // - Packet loss
147 // - Input lag
148 // - Unstable connection
149 //
150 // • For real-time control, call Update() every loop iteration
151 // without any blocking operations
152 //
153 // 🔴【重要】Update() 必须在 loop() 中尽可能高频调用
154 // • Update() 负责处理来自 CodexPad 的蓝牙数据包
155 // • 任何形式的 delay 或阻塞代码都会导致:
156 // - 数据丢失
157 // - 响应延迟
158 // - 连接不稳定
159 //
160 // • 实时控制应用中,必须每轮循环都调用 Update(),不可阻塞
161 // ==========================================================================
162 const gamepad::input::Tracker& it = g_codex_pad_client.Update();
163 // ==========================================================================
164 // Tracker: Gamepad Input Snapshot & Change Engine
165 // ==========================================================================
166 // • Returned by Update()
167 // • Maintains previous and current input snapshots
168 // • Enables edge detection and delta detection
169 //
170 // Tracker 由 Update() 返回
171 // 内部保存上一帧和当前帧的输入数据
172 // 支持边沿检测和差值检测
173 //
174 // 📚 https://codexpad.github.io/gamepad_input_arduino_lib/
175 // ==========================================================================
176
177 if (!g_codex_pad_client.is_connected()) {
178 CLOGW("Disconnected, start to reconnect");
179 Connect();
180 return;
181 }
182
183 RssiMonitor();
184
185 // ==========================================================================
186 // 🟢 Button State Change Detection (Edge-Based)
187 // ==========================================================================
188 // • pressed() → button was just pressed (released → pressed)
189 // • released() → button was just released (pressed → released)
190 // • holding() → button remains pressed across frames
191 //
192 // These APIs are *frame-differential* and rely on Update() frequency.
193 // Ideal for UI navigation, action triggers, and avoiding repeat firing.
194 //
195 // • pressed() → 按钮刚被按下(弹起 → 按下)
196 // • released() → 按钮刚被释放(按下 → 弹起)
197 // • holding() → 按钮在两帧之间持续按下
198 //
199 // 这些接口是“帧间差分”的,依赖于 Update() 的高频调用
200 // 非常适合 UI 导航、动作触发和防止长按连发
201 // ==========================================================================
202
203 static std::map<Button, uint64_t> s_button_last_time;
204
205 for (const auto& [button, name] : kButtonNames) {
206 if (it.pressed(button)) { // button was just pressed
207 CLOGI("Button mask: 0x%08" PRIX32 ", button %s: pressed", it.button_mask(), name.c_str());
208 s_button_last_time[button] = millis();
209 } else if (it.released(button)) { // button was just released
210 CLOGI("Button mask: 0x%08" PRIX32 ", button %s: released", it.button_mask(), name.c_str());
211 s_button_last_time[button] = millis();
212 } else if (it.holding(button)) { // button remains pressed
213 if (s_button_last_time.find(button) == s_button_last_time.end() || s_button_last_time[button] == 0 ||
214 millis() - s_button_last_time[button] > 100) {
215 CLOGI("Button mask: 0x%08" PRIX32 ", button %s: holding", it.button_mask(), name.c_str());
216 s_button_last_time[button] = millis();
217 }
218 }
219 }
220
221 // ==========================================================================
222 // 🟢 Joystick Axis Change Detection (Threshold-Based Filtering)
223 // ==========================================================================
224 // • AxisChanged() detects significant changes between frames
225 // • Uses a threshold to filter out noise and minor jitter
226 // • Only reports movement when change ≥ threshold
227 //
228 // • AxisChanged() 用于检测摇杆轴值的有效变化
229 // • 使用阈值过滤微小抖动和噪声
230 // • 只有当变化幅度 ≥ 阈值时才视为有效移动
231 // ==========================================================================
232 constexpr uint8_t kAxisValueChangeThreshold = 5;
233
234 if (it.AxisChanged(Axis::kLeftStickX, kAxisValueChangeThreshold) ||
235 it.AxisChanged(Axis::kLeftStickY, kAxisValueChangeThreshold) ||
236 it.AxisChanged(Axis::kRightStickX, kAxisValueChangeThreshold) ||
237 it.AxisChanged(Axis::kRightStickY, kAxisValueChangeThreshold)) {
238 CLOGI("L(X: %3" PRIu8 ", Y:%3" PRIu8 "), R(X: %3" PRIu8 ", Y: %3" PRIu8 ")", it[Axis::kLeftStickX], it[Axis::kLeftStickY],
239 it[Axis::kRightStickX], it[Axis::kRightStickY]);
240 }
241}
Client main class.
Definition client.h:25
const gamepad::input::Tracker & Update() noexcept
Update, need to be called in Loop.
Definition client.cpp:118
const std::string & remote_device_name() const noexcept
Get model number of the CodexPad.
Definition client.h:176
void Init(int8_t local_tx_power=3) noexcept
Initialize.
Definition client.cpp:41
const std::array< uint8_t, 3 > & remote_firmware_version() const noexcept
Get firmware version of the CodexPad.
Definition client.h:200
bool is_connected() const noexcept
Is connected.
Definition client.cpp:143
NimBLEClient * ble_client() const noexcept
Get the BLE client object.
Definition client.h:241
bool Connect(const std::string &bluetooth_device_address, uint32_t timeout_ms=5000) noexcept
Connect.
Definition client.cpp:48
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