CodexPad Arduino 库 4.0.0
载入中...
搜索中...
未找到
basic_polling.ino
浏览该文件的文档.
1/**
2 * @~English
3 * @file basic_polling.ino
4 * @example basic_polling.ino
5 * @brief Demonstrates the basic polling method to periodically query and print all CodexPad button states and joystick values.
6 * @details This example establishes a connection to a specific CodexPad device (by Bluetooth Device Address) and implements a
7 * simple polling loop. Every 50 milliseconds, it queries and prints the current state (pressed/released) of all
8 * buttons and the raw analog values (0-255) of both joysticks. It showcases the fundamental usage of
9 * `gamepad::input::Tracker[Button]` for discrete button queries and `gamepad::input::Tracker[Axis]` for continuous
10 * joystick readings.
11 * @note This example uses a simple timing mechanism (`millis()`) to print at a fixed interval, which is suitable for
12 * monitoring or logging. For real-time control, ensure `Update()` is called as frequently as possible without blocking
13 * delays.
14 * @see codex_pad::Client::Update
15 */
16/**
17 * @~Chinese
18 * @file basic_polling.ino
19 * @example basic_polling.ino
20 * @brief 演示通过基本轮询方式定期查询并打印手柄所有按钮状态与摇杆值。
21 * @details 本示例通过地址连接到指定的手柄,并实现了一个简单的轮询循环。
22 * 每隔 50 毫秒,它会查询并打印所有按钮的当前状态(按下/弹起)以及两个摇杆的原始模拟值(0-255)。
23 * 它展示了 `gamepad::input::Tracker[Button]` 用于离散按钮查询和 `gamepad::input::Tracker[Axis]`
24 * 用于连续摇杆读取的基本用法。
25 * @note 本示例使用简单的定时机制(`millis()`)以固定间隔打印,适用于状态监控或日志记录。
26 * 对于实时控制应用,请确保尽可能频繁地调用 `Update()` 且无阻塞延时。
27 * @see codex_pad::Client::Update
28 */
29
30#include <string>
31
32#include "codex_pad.h"
33#include "cyf.h"
34#include "cyf/log.h"
35
36/**
37 * IMPORTANT:
38 * This using directive is REQUIRED to directly access `Button` and `Axis`.
39 * Without it, you must write the fully qualified names:
40 * gamepad::input::Button::kUp
41 * gamepad::input::Axis::kLeftStickX
42 * Forgetting this line will cause compile errors when using Button or Axis.
43 */
44/**
45 * 重要:
46 * 必须使用该命名空间,否则无法直接访问 `Button` 和 `Axis`。
47 * 如果没有这一行,就必须写成完整限定名:
48 * gamepad::input::Button::kUp
49 * gamepad::input::Axis::kLeftStickX
50 * 忘记引入命名空间会导致编译失败。
51 */
52using namespace gamepad::input; // ⚠️ DO NOT REMOVE THIS LINE ⚠️
53
54namespace {
55// Replace with your CodexPad device's Bluetooth device address
56// 替换为你的 CodexPad 的 Bluetooth device address
57const std::string kBluetoothDeviceAddress = "E4:66:E5:A2:17:06";
58
59codex_pad::Client g_codex_pad_client;
60
61void Connect() {
62 CLOGI("Start to connect %s", kBluetoothDeviceAddress.c_str());
63 // Connect to the CodexPad with specified Bluetooth device address
64 // 连接到指定蓝牙设备地址的手柄
65 while (!g_codex_pad_client.Connect(kBluetoothDeviceAddress, 5000)) {
66 CLOGI("Retry to connect %s", kBluetoothDeviceAddress.c_str());
67 }
68
69 CLOGI("Remote device name: %s", g_codex_pad_client.remote_device_name().c_str());
70 CLOGI("Remote model number: %s", g_codex_pad_client.remote_model_number().c_str());
71 CLOGI("Remote firmware revision: %u.%u.%u", g_codex_pad_client.remote_firmware_version()[0],
72 g_codex_pad_client.remote_firmware_version()[1], g_codex_pad_client.remote_firmware_version()[2]);
73
74 if (const auto ble_client = g_codex_pad_client.ble_client(); ble_client != nullptr) {
75 CLOGI("Remote Bluetooth Device Address: %s", ble_client->getPeerAddress().toString().c_str());
76 } else {
77 CLOGI("Remote Bluetooth Device Address: unknown");
78 }
79
80 CLOGI("Connected");
81}
82} // namespace
83
84void setup() {
85 Serial.begin(115200);
86
87 printf("Init\n");
88 g_codex_pad_client.Init();
89
90 Connect();
91}
92
93void loop() {
94 // ==========================================================================
95 // 🔴 CRITICAL: Call Update() as frequently as possible in loop()
96 // ==========================================================================
97 // • Update() processes incoming Bluetooth packets from the CodexPad
98 // • Any delay(...) or long blocking code WILL cause:
99 // - Packet loss
100 // - Input lag
101 // - Unstable connection
102 //
103 // • For real-time control, call Update() every loop iteration
104 // without any blocking operations
105 //
106 // 🔴【重要】Update() 必须在 loop() 中尽可能高频调用
107 // • Update() 负责处理来自 CodexPad 的蓝牙数据包
108 // • 任何形式的 delay 或阻塞代码都会导致:
109 // - 数据丢失
110 // - 响应延迟
111 // - 连接不稳定
112 //
113 // • 实时控制应用中,必须每轮循环都调用 Update(),不可阻塞
114 // ==========================================================================
115 const gamepad::input::Tracker& it = g_codex_pad_client.Update();
116 // ==========================================================================
117 // Tracker: Access button and joystick states
118 // ==========================================================================
119 // • Returned Tracker provides access to ALL gamepad inputs
120 // • Buttons → it[Button::kXXX] (bool, true = pressed)
121 // • Axes → it[Axis::kXXX] (uint8_t, 0–255)
122 //
123 // 📚 GamepadInput Library Documentation:
124 // https://codexpad.github.io/gamepad_input_arduino_lib/
125 //
126 // • Tracker 可用于访问所有按钮和摇杆状态
127 // • 按钮 → it[Button::kXXX](bool,true 表示按下)
128 // • 摇杆轴 → it[Axis::kXXX](0~255)
129 //
130 // 📘 库文档:
131 // https://codexpad.github.io/gamepad_input_arduino_lib/
132 // ==========================================================================
133
134 if (!g_codex_pad_client.is_connected()) {
135 CLOGW("Disconnected, start to reconnect\n");
136 Connect();
137 return;
138 }
139
140 static uint32_t s_print_time = 0;
141 if (s_print_time != 0 && s_print_time + 50 > millis()) {
142 return;
143 }
144
145 s_print_time = millis();
146
147 std::string log;
148
149 char buffer[512] = {0};
150 size_t length = snprintf(buffer, sizeof(buffer), "Button mask: 0x%08" PRIX32, static_cast<uint32_t>(it.raw().buttons));
151 log.append(buffer, length);
152
153 // ------------------------------------------------------------------
154 // Joystick axis values (0–255)
155 // Center position ≈ 128
156 // Smaller → left / down
157 // Larger → right / up
158 //
159 // 摇杆轴数据(0~255)
160 // 中间值约 128
161 // 越小越左 / 下,越大越右 / 上
162 // ------------------------------------------------------------------
163 length = snprintf(buffer, sizeof(buffer), ", L(%3u, %3u), R(%3u, %3u)", it[Axis::kLeftStickX], it[Axis::kLeftStickY],
164 it[Axis::kRightStickX], it[Axis::kRightStickY]);
165 log.append(buffer, length);
166
167 // ------------------------------------------------------------------
168 // Button states (boolean -> uint)
169 // operator[] returns bool:
170 // true = pressed
171 // false = released
172 //
173 // 按钮状态(bool 类型,打印时被隐式转换为 1 / 0)
174 // true : 按下
175 // false : 弹起
176 if (it[Button::kUp]) {
177 log.append(", Up");
178 }
179
180 if (it[Button::kDown]) {
181 log.append(", Down");
182 }
183
184 if (it[Button::kLeft]) {
185 log.append(", Left");
186 }
187
188 if (it[Button::kRight]) {
189 log.append(", Right");
190 }
191
192 if (it[Button::kSquareX]) {
193 log.append(", Square(X)");
194 }
195
196 if (it[Button::kTriangleY]) {
197 log.append(", Triangle(Y)");
198 }
199
200 if (it[Button::kCrossA]) {
201 log.append(", Cross(A)");
202 }
203
204 if (it[Button::kCircleB]) {
205 log.append(", Circle(B)");
206 }
207
208 if (it[Button::kL1]) {
209 log.append(", L1");
210 }
211
212 if (it[Button::kL2]) {
213 log.append(", L2");
214 }
215
216 if (it[Button::kL3]) {
217 log.append(", L3");
218 }
219
220 if (it[Button::kR1]) {
221 log.append(", R1");
222 }
223
224 if (it[Button::kR2]) {
225 log.append(", R2");
226 }
227
228 if (it[Button::kR3]) {
229 log.append(", R3");
230 }
231
232 if (it[Button::kSelect]) {
233 log.append(", Select");
234 }
235
236 if (it[Button::kStart]) {
237 log.append(", Start");
238 }
239
240 if (it[Button::kHome]) {
241 log.append(", Home");
242 }
243
244 CLOGI("%s", log.c_str());
245}
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
初始化
bool Connect(const std::string &bluetooth_device_address, uint32_t timeout_ms=5000) noexcept
连接
const std::string & remote_model_number() const noexcept
获取CodexPad的型号