CodexPad Arduino 库 4.2.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 CLOGI("Init");
88
89 // Set the TX power for the local BLE device (e.g., ESP32) in dBm.
90 // 9dBm is the maximum TX power for ESP32 in BLE mode, which helps improve signal coverage.
91 // NimBLETxPowerType::All applies this power level to both advertising and connection channels.
92 const int8_t local_tx_power = 9; // Local device TX power in dBm
93 g_codex_pad_client.Init(local_tx_power);
94
95 Connect();
96}
97
98void loop() {
99 // ==========================================================================
100 // 🔴 CRITICAL: Call Update() as frequently as possible in loop()
101 // ==========================================================================
102 // • Update() processes incoming Bluetooth packets from the CodexPad
103 // • Any delay(...) or long blocking code WILL cause:
104 // - Packet loss
105 // - Input lag
106 // - Unstable connection
107 //
108 // • For real-time control, call Update() every loop iteration
109 // without any blocking operations
110 //
111 // 🔴【重要】Update() 必须在 loop() 中尽可能高频调用
112 // • Update() 负责处理来自 CodexPad 的蓝牙数据包
113 // • 任何形式的 delay 或阻塞代码都会导致:
114 // - 数据丢失
115 // - 响应延迟
116 // - 连接不稳定
117 //
118 // • 实时控制应用中,必须每轮循环都调用 Update(),不可阻塞
119 // ==========================================================================
120 const gamepad::input::Tracker& it = g_codex_pad_client.Update();
121 // ==========================================================================
122 // Tracker: Access button and joystick states
123 // ==========================================================================
124 // • Returned Tracker provides access to ALL gamepad inputs
125 // • Buttons → it[Button::kXXX] (bool, true = pressed)
126 // • Axes → it[Axis::kXXX] (uint8_t, 0–255)
127 //
128 // 📚 GamepadInput Library Documentation:
129 // https://codexpad.github.io/gamepad_input_arduino_lib/
130 //
131 // • Tracker 可用于访问所有按钮和摇杆状态
132 // • 按钮 → it[Button::kXXX](bool,true 表示按下)
133 // • 摇杆轴 → it[Axis::kXXX](0~255)
134 //
135 // 📘 库文档:
136 // https://codexpad.github.io/gamepad_input_arduino_lib/
137 // ==========================================================================
138
139 if (!g_codex_pad_client.is_connected()) {
140 CLOGW("Disconnected, start to reconnect\n");
141 Connect();
142 return;
143 }
144
145 static uint32_t s_print_time = 0;
146 if (s_print_time != 0 && s_print_time + 50 > millis()) {
147 return;
148 }
149
150 s_print_time = millis();
151
152 std::string log;
153
154 char buffer[512] = {0};
155 size_t length = snprintf(buffer, sizeof(buffer), "Button mask: 0x%08" PRIX32, static_cast<uint32_t>(it.button_mask()));
156 log.append(buffer, length);
157
158 // ------------------------------------------------------------------
159 // Joystick axis values (0–255)
160 // Center position ≈ 128
161 // Smaller → left / down
162 // Larger → right / up
163 //
164 // 摇杆轴数据(0~255)
165 // 中间值约 128
166 // 越小越左 / 下,越大越右 / 上
167 // ------------------------------------------------------------------
168 length = snprintf(buffer, sizeof(buffer), ", L(%3u, %3u), R(%3u, %3u)", it[Axis::kLeftStickX], it[Axis::kLeftStickY],
169 it[Axis::kRightStickX], it[Axis::kRightStickY]);
170 log.append(buffer, length);
171
172 // ------------------------------------------------------------------
173 // Button states (boolean -> uint)
174 // operator[] returns bool:
175 // true = pressed
176 // false = released
177 //
178 // 按钮状态(bool 类型)
179 // true : 按下
180 // false : 弹起
181 if (it[Button::kUp]) {
182 log.append(", Up");
183 }
184
185 if (it[Button::kDown]) {
186 log.append(", Down");
187 }
188
189 if (it[Button::kLeft]) {
190 log.append(", Left");
191 }
192
193 if (it[Button::kRight]) {
194 log.append(", Right");
195 }
196
197 if (it[Button::kSquareX]) {
198 log.append(", Square(X)");
199 }
200
201 if (it[Button::kTriangleY]) {
202 log.append(", Triangle(Y)");
203 }
204
205 if (it[Button::kCrossA]) {
206 log.append(", Cross(A)");
207 }
208
209 if (it[Button::kCircleB]) {
210 log.append(", Circle(B)");
211 }
212
213 if (it[Button::kL1]) {
214 log.append(", L1");
215 }
216
217 if (it[Button::kL2]) {
218 log.append(", L2");
219 }
220
221 if (it[Button::kL3]) {
222 log.append(", L3");
223 }
224
225 if (it[Button::kR1]) {
226 log.append(", R1");
227 }
228
229 if (it[Button::kR2]) {
230 log.append(", R2");
231 }
232
233 if (it[Button::kR3]) {
234 log.append(", R3");
235 }
236
237 if (it[Button::kSelect]) {
238 log.append(", Select");
239 }
240
241 if (it[Button::kStart]) {
242 log.append(", Start");
243 }
244
245 if (it[Button::kHome]) {
246 log.append(", Home");
247 }
248
249 CLOGI("%s", log.c_str());
250}
Client主类
const gamepad::input::Tracker & Update() noexcept
更新,需要在Loop中不断调用
const std::string & remote_device_name() const noexcept
获取CodexPad的型号
void Init(int8_t local_tx_power=3) noexcept
初始化
const std::array< uint8_t, 3 > & remote_firmware_version() const noexcept
获取CodexPad的固件版本
bool is_connected() const noexcept
是否连接
NimBLEClient * ble_client() const noexcept
获取 BLE 客户端对象
bool Connect(const std::string &bluetooth_device_address, uint32_t timeout_ms=5000) noexcept
连接
const std::string & remote_model_number() const noexcept
获取CodexPad的型号