UartClient Read Battery#
What you’ll do
배터리 전압 요청(보조 명령)을 주기적으로 전송하고,
poll()로 응답을 받아 출력합니다.
Prerequisites
Next
이 튜토리얼은 UartClient Read Speed에서 다룬 포트 open/flush, 루프 뼈대를 그대로 사용하고, 배터리 전압 요청(보조 명령) 처리만 정리합니다.
1. 목표#
배터리 전압 요청(보조 명령)을 주기적으로 전송
poll()로BatteryVoltage를 받아 출력
2. 단계별 구현 가이드#
단계 1) 포트 open/flush#
UartClient Read Speed와 동일합니다. 아래 API만 재사용합니다.
KMC_HARDWARE::UartClient client;
client.open(port, 115200);
client.flushInput();
단계 2) 배터리 요청 → 응답 대기 → 출력#
const auto cycle_start = std::chrono::steady_clock::now();
client.requestBatteryVoltage();
const auto deadline = cycle_start + std::chrono::milliseconds(200);
bool printed = false;
while (std::chrono::steady_clock::now() < deadline) {
auto msg = client.poll(50);
if (!msg) continue;
if (auto* bv = std::get_if<KMC_HARDWARE::BatteryVoltage>(&*msg)) {
std::printf("BatteryVoltage: %.2f V\n", bv->volt);
printed = true;
break;
}
}
단계 3) 주기 유지 (\(1\,\mathrm{Hz}\))#
const auto elapsed = std::chrono::steady_clock::now() - cycle_start;
const auto period = std::chrono::seconds(1);
if (elapsed < period) {
std::this_thread::sleep_for(period - elapsed);
}
3. Result#
아래 코드는 SDK 리포지토리의 examples/UartClient_Advanced/read_battery.cpp와 동일한 내용입니다.
#include "KMC_uart_client.hpp"
#include <chrono>
#include <cstdio>
#include <string>
#include <thread>
#include <variant>
int main(int argc, char **argv) {
const std::string port = (argc > 1) ? argv[1] : "/dev/ttyKMC";
KMC_HARDWARE::UartClient client;
if (!client.open(port, 115200)) {
std::fprintf(stderr, "Failed to open port: %s\n", port.c_str());
return 1;
}
client.flushInput();
while (true) {
const auto cycle_start = std::chrono::steady_clock::now();
client.requestBatteryVoltage();
const auto deadline = cycle_start + std::chrono::milliseconds(200);
bool printed = false;
while (std::chrono::steady_clock::now() < deadline) {
auto msg = client.poll(50);
if (!msg) {
continue;
}
if (auto* bv = std::get_if<KMC_HARDWARE::BatteryVoltage>(&*msg)) {
std::printf("BatteryVoltage: %.2f V\n", bv->volt);
printed = true;
break;
}
}
if (!printed) {
std::printf("BatteryVoltage: (no response)\n");
}
const auto elapsed = std::chrono::steady_clock::now() - cycle_start;
const auto period = std::chrono::seconds(1);
if (elapsed < period) {
std::this_thread::sleep_for(period - elapsed);
}
}
return 0;
}