演示通过基本轮询方式定期查询并打印手柄所有按钮状态与摇杆值。 本示例通过地址连接到指定的手柄,并实现了一个简单的轮询循环。 每隔 50 毫秒,它会查询并打印所有按钮的当前状态(按下/弹起)以及两个摇杆的原始模拟值(0-255)。 它展示了 gamepad::input::Tracker[Button] 用于离散按钮查询和 gamepad::input::Tracker[Axis] 用于连续摇杆读取的基本用法。
#include <string>
#include "codex_pad.h"
#include "cyf.h"
#include "cyf/log.h"
using namespace gamepad::input;
namespace {
const std::string kBluetoothDeviceAddress = "E4:66:E5:A2:17:06";
void Connect() {
CLOGI("Start to connect %s", kBluetoothDeviceAddress.c_str());
while (!g_codex_pad_client.
Connect(kBluetoothDeviceAddress, 5000)) {
CLOGI("Retry to connect %s", kBluetoothDeviceAddress.c_str());
}
if (
const auto ble_client = g_codex_pad_client.
ble_client(); ble_client !=
nullptr) {
CLOGI("Remote Bluetooth Device Address: %s", ble_client->getPeerAddress().toString().c_str());
} else {
CLOGI("Remote Bluetooth Device Address: unknown");
}
CLOGI("Connected");
}
}
void setup() {
Serial.begin(115200);
printf("Init\n");
g_codex_pad_client.Init();
Connect();
}
void loop() {
const gamepad::input::Tracker& it = g_codex_pad_client.Update();
if (!g_codex_pad_client.is_connected()) {
CLOGW("Disconnected, start to reconnect\n");
Connect();
return;
}
static uint32_t s_print_time = 0;
if (s_print_time != 0 && s_print_time + 50 > millis()) {
return;
}
s_print_time = millis();
std::string log;
char buffer[512] = {0};
size_t length = snprintf(buffer, sizeof(buffer), "Button mask: 0x%08" PRIX32, static_cast<uint32_t>(it.raw().buttons));
log.append(buffer, length);
length = snprintf(buffer, sizeof(buffer), ", L(%3u, %3u), R(%3u, %3u)", it[Axis::kLeftStickX], it[Axis::kLeftStickY],
it[Axis::kRightStickX], it[Axis::kRightStickY]);
log.append(buffer, length);
if (it[Button::kUp]) {
log.append(", Up");
}
if (it[Button::kDown]) {
log.append(", Down");
}
if (it[Button::kLeft]) {
log.append(", Left");
}
if (it[Button::kRight]) {
log.append(", Right");
}
if (it[Button::kSquareX]) {
log.append(", Square(X)");
}
if (it[Button::kTriangleY]) {
log.append(", Triangle(Y)");
}
if (it[Button::kCrossA]) {
log.append(", Cross(A)");
}
if (it[Button::kCircleB]) {
log.append(", Circle(B)");
}
if (it[Button::kL1]) {
log.append(", L1");
}
if (it[Button::kL2]) {
log.append(", L2");
}
if (it[Button::kL3]) {
log.append(", L3");
}
if (it[Button::kR1]) {
log.append(", R1");
}
if (it[Button::kR2]) {
log.append(", R2");
}
if (it[Button::kR3]) {
log.append(", R3");
}
if (it[Button::kSelect]) {
log.append(", Select");
}
if (it[Button::kStart]) {
log.append(", Start");
}
if (it[Button::kHome]) {
log.append(", Home");
}
CLOGI("%s", log.c_str());
}
const std::string & remote_device_name() const noexcept
获取CodexPad的型号
const std::array< uint8_t, 3 > & remote_firmware_version() const noexcept
获取CodexPad的固件版本
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的型号