CodexPad Arduino Lib 4.0.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 Connect();
132}
133
134void loop() {
135 // ==========================================================================
136 // 🔴 CRITICAL: Call Update() as frequently as possible in loop()
137 // ==========================================================================
138 // • Update() processes incoming Bluetooth packets from the CodexPad
139 // • Any delay(...) or long blocking code WILL cause:
140 // - Packet loss
141 // - Input lag
142 // - Unstable connection
143 //
144 // • For real-time control, call Update() every loop iteration
145 // without any blocking operations
146 //
147 // 🔴【重要】Update() 必须在 loop() 中尽可能高频调用
148 // • Update() 负责处理来自 CodexPad 的蓝牙数据包
149 // • 任何形式的 delay 或阻塞代码都会导致:
150 // - 数据丢失
151 // - 响应延迟
152 // - 连接不稳定
153 //
154 // • 实时控制应用中,必须每轮循环都调用 Update(),不可阻塞
155 // ==========================================================================
156 const gamepad::input::Tracker& it = g_codex_pad_client.Update();
157 // ==========================================================================
158 // Tracker: Gamepad Input Snapshot & Change Engine
159 // ==========================================================================
160 // • Returned by Update()
161 // • Maintains previous and current input snapshots
162 // • Enables edge detection and delta detection
163 //
164 // Tracker 由 Update() 返回
165 // 内部保存上一帧和当前帧的输入数据
166 // 支持边沿检测和差值检测
167 //
168 // 📚 https://codexpad.github.io/gamepad_input_arduino_lib/
169 // ==========================================================================
170
171 if (!g_codex_pad_client.is_connected()) {
172 CLOGW("Disconnected, start to reconnect");
173 Connect();
174 return;
175 }
176
177 RssiMonitor();
178
179 // ==========================================================================
180 // 🟢 Button State Change Detection (Edge-Based)
181 // ==========================================================================
182 // • pressed() → button was just pressed (released → pressed)
183 // • released() → button was just released (pressed → released)
184 // • holding() → button remains pressed across frames
185 //
186 // These APIs are *frame-differential* and rely on Update() frequency.
187 // Ideal for UI navigation, action triggers, and avoiding repeat firing.
188 //
189 // • pressed() → 按钮刚被按下(弹起 → 按下)
190 // • released() → 按钮刚被释放(按下 → 弹起)
191 // • holding() → 按钮在两帧之间持续按下
192 //
193 // 这些接口是“帧间差分”的,依赖于 Update() 的高频调用
194 // 非常适合 UI 导航、动作触发和防止长按连发
195 // ==========================================================================
196
197 static std::map<Button, uint64_t> s_button_last_time;
198
199 for (const auto& [button, name] : kButtonNames) {
200 if (it.pressed(button)) { // button was just pressed
201 CLOGI("Button mask: 0x%08" PRIX32 ", button %s: pressed", it.raw().buttons, name.c_str());
202 s_button_last_time[button] = millis();
203 } else if (it.released(button)) { // button was just released
204 CLOGI("Button mask: 0x%08" PRIX32 ", button %s: released", it.raw().buttons, name.c_str());
205 s_button_last_time[button] = millis();
206 } else if (it.holding(button)) { // button remains pressed
207 if (s_button_last_time.find(button) == s_button_last_time.end() || s_button_last_time[button] == 0 ||
208 millis() - s_button_last_time[button] > 100) {
209 CLOGI("Button mask: 0x%08" PRIX32 ", button %s: holding", it.raw().buttons, name.c_str());
210 s_button_last_time[button] = millis();
211 }
212 }
213 }
214
215 // ==========================================================================
216 // 🟢 Joystick Axis Change Detection (Threshold-Based Filtering)
217 // ==========================================================================
218 // • AxisChanged() detects significant changes between frames
219 // • Uses a threshold to filter out noise and minor jitter
220 // • Only reports movement when change ≥ threshold
221 //
222 // • AxisChanged() 用于检测摇杆轴值的有效变化
223 // • 使用阈值过滤微小抖动和噪声
224 // • 只有当变化幅度 ≥ 阈值时才视为有效移动
225 // ==========================================================================
226 constexpr uint8_t kAxisValueChangeThreshold = 5;
227
228 if (it.AxisChanged(Axis::kLeftStickX, kAxisValueChangeThreshold) ||
229 it.AxisChanged(Axis::kLeftStickY, kAxisValueChangeThreshold) ||
230 it.AxisChanged(Axis::kRightStickX, kAxisValueChangeThreshold) ||
231 it.AxisChanged(Axis::kRightStickY, kAxisValueChangeThreshold)) {
232 CLOGI("L(X: %3" PRIu8 ", Y:%3" PRIu8 "), R(X: %3" PRIu8 ", Y: %3" PRIu8 ")", it[Axis::kLeftStickX], it[Axis::kLeftStickY],
233 it[Axis::kRightStickX], it[Axis::kRightStickY]);
234 }
235}
Client main class.
Definition client.h:25
const gamepad::input::Tracker & Update() noexcept
Update, need to be called in Loop.
Definition client.cpp:117
const std::string & remote_device_name() const noexcept
Get model number of the CodexPad.
Definition client.h:174
const std::array< uint8_t, 3 > & remote_firmware_version() const noexcept
Get firmware version of the CodexPad.
Definition client.h:198
bool is_connected() const noexcept
Is connected.
Definition client.cpp:142
NimBLEClient * ble_client() const noexcept
Get the BLE client object.
Definition client.h:239
void Init() noexcept
Initialize.
Definition client.cpp:41
bool Connect(const std::string &bluetooth_device_address, uint32_t timeout_ms=5000) noexcept
Connect.
Definition client.cpp:47
const std::string & remote_model_number() const noexcept
Get model number of the CodexPad.
Definition client.h:186
int32_t rssi() const noexcept
Get the RSSI of the CodexPad.
Definition client.cpp:229