Wiki
Serial Communication Serial Packet Protocol Example
Existing English translations were reused. 8 current source blocks remain in Simplified Chinese, without triggering paid translation.
串口是机器人里最常见的通信方式之一:上位机 ROS2 / Linux 程序通过 USB-TTL、USB-CAN 转串口、CH340、CP2102、FT232 等设备和 STM32、ESP32、下位机控制板通信。
This section still follows the order of "first prepare the environment, then see how to call it, and finally run and observe the results":
克隆 Serial_Pack
先学 ROS2 端串口驱动:打开、接收、发送
再学跨平台串口包协议:注册命令、打包、解包
最后用虚拟串口或 STM32 验证
Serial port reception and asynchronous callbacks such as ROS2 timers uniformly use std::bind. The protocol's command handler functions require explicit parameter types; register ordinary functions or member functions directly.
1.Get Project
第一次拿到项目,先只克隆这一个仓库。下面统一以克隆到用户主目录的 ~/Serial_Pack 为例:
cd ~
git clone https://github.com/tungchiahui/Serial_Pack.git
cd Serial_Pack
本教程会用到以下文件,路径都从 Serial_Pack/ 算起:
example/ros2_ws/src/serial_comm/ ROS2 演示节点
example/ros2_ws/src/serial_transport/ PC 端串口驱动
example/ros2_ws/src/wire_protocol/ 不依赖 ROS2 的 C++20 串口包协议
example/stm32_hal/ STM32CubeMX + HAL 接入例程
Only this repository is needed. On the PC side, use the ready-made ROS2 workspace; on the STM32 side, generate the project with CubeMX from example/stm32_hal/TEST.ioc, then integrate the applications , bsp and cmake/user in the same directory.
2.Preparing the ASIO library under Linux
2.1.This library depends only on standalone asio.
Ubuntu / Debian:
sudo apt install libasio-dev
Fedora:
sudo dnf install asio-devel
2.2.Install the full Boost library (not really necessary for a complete program)
Ubuntu / Debian:
sudo apt install libboost-all-dev
Fedora:
sudo dnf install boost-devel
3.Preparing a Virtual Serial Port Test Environment on Linux
If you do not have a real STM32 on hand, you can use socat to create a pair of virtual serial ports.
3.1.Install socat
Ubuntu / Debian:
sudo apt install socat
Fedora:
sudo dnf install socat
3.2.Create a pair of virtual serial ports
Open a new terminal and run:
socat -d -d \
PTY,raw,echo=0,link=/tmp/ttyV0 \
PTY,raw,echo=0,link=/tmp/ttyV1
You will see output similar to:
2026/05/24 12:00:00 socat[12345] N PTY is /dev/pts/3
2026/05/24 12:00:00 socat[12345] N PTY is /dev/pts/4
2026/05/24 12:00:00 socat[12345] N starting data transfer loop with FDs [5,5] and [7,7]
This indicates:
/dev/pts/3 和 /dev/pts/4 是一对互通的虚拟串口
程序写 /dev/pts/3,另一个终端读 /dev/pts/4 就能看到
程序读 /dev/pts/3,另一个终端写 /dev/pts/4 就能发给程序
同时我也给了他们别名
/dev/pts/3 和 /tmp/ttyV0是同一个东西
/dev/pts/4 和 /tmp/ttyV1是同一个东西
The following example uses /tmp/ttyV0 and /tmp/ttyV1; there is no need to guess the changing /dev/pts/N each time. Keep this socat terminal running.
4.Part 1: ROS2 Terminal Serial Driver serial_transport
4.1.Program Objectives
First, focus on just one thing: ROS2 how a node opens a serial port, receives a segment of bytes, and sends a segment of bytes. At this point, there is no need to understand the contents of the serial packet; the next part will explain "bytes" as commands and fields.
There are mainly two types made publicly available to us on the PC side:
serial_transport::Serial_Config: Save the device name, baud rate, data bits, parity bit, stop bits, and flow control. This example uses 115200 8N1, no flow control.serial_transport::SerialTransport: Providesstart(config, 回调),async_write(字节)andstop().
4.2.First, look at the call sequence (pseudocode).
Here, intentionally only the usage sequence is written, without expanding on the Asio thread and serial driver source code:
ROS2 节点初始化:
从参数读取 port 和 baud_rate
填写 Serial_Config:设备名、115200、8N1、无流控
driver.start(config, std::bind(本节点的接收函数, this, 第一个参数))
接收函数(本次收到的字节片段):
把片段交给后面的协议 feed()
需要发送时:
driver.async_write(待发送的字节)
节点退出时:
driver.stop()
These calls correspond to example/ros2_ws/src/serial_comm/src/serial_comm.cpp in serial_config_ and serial_driver_. The example reads the device name and baud rate from the ROS2 parameter port and baud_rate in the example, with the remaining configuration fixed to 8N1 and no flow control.
4.3.Key Function Description
4.3.1.SerialTransport::start()
Function prototype:
bool start(
Serial_Config config,
std::function<void(std::span<const uint8_t>)> receive_callback);
Function: Starts the serial port driver, attempts to open the device according to the configuration, and begins asynchronous reception. After bytes are received, the reception callback is invoked.
Parameters:
config:Serial_Config; serial port configuration, including device nameport_name_; baud ratebaud_rate_; data bitscharacter_size_; parityparity_; stop bitsstop_bits_and flow controlflow_control_.receive_callback:std::function<void(std::span<const uint8_t>)>; the function to execute when bytes are received. Its parameter is the received byte fragment this time; a complete frame is not guaranteed.std::spandoes not own the data and is only used within this callback; copy it yourself if you need to retain it.
返回值:bool。首次启动返回 true;同一个驱动对象已经启动时返回 false。true 只表示启动流程已提交,不代表物理串口已经打开。设备暂时不存在时驱动会尝试重连,要以终端的 串口打开成功 日志确认实际打开。
4.3.2.SerialTransport::async_write()
Function prototype:
void async_write(std::span<const uint8_t> frame);
Purpose: submit a segment of bytes to the serial port driver for asynchronous transmission.
Parameters:
frame:std::span<const uint8_t>,表示待发送字节的起始位置和长度。可以传pack()返回的std::array;当前驱动在调用时会复制这段数据,所以局部帧数组在函数返回后可以销毁。
Return value:void,没有发送成功状态。这次调用不等待对端确认;如果物理串口尚未打开,提交的帧不会在重连后补发。
4.3.3.SerialTransport::stop()
Function prototype:
void stop();
Function: Stop receiving, close the serial port, and wait for the driver thread to exit.
Parameters: none.
Return value:void。SerialTransport It is also called during destruction; the node object used by the receiving callback must remain alive until after the driver stops.
Up to this point, we only know how to move bytes around. The next step is to resolve "which bytes belong to the same command, and who handles them after they are received."
5.Part 2: Cross-platform Serial Port Packet Communication Protocol wire_protocol
wire_protocol is pure C++20: ROS2/Linux programs can be used, and STM32 projects supported by C++20 can also be used. Both ends use the same set of pack()、feed()、set_unpack_callback() and each uses its own serial port driver to move bytes. Users do not need to handle partial packets, packet sticking, and checksums themselves, nor do they need to read the protocol parsing source code.
5.1.Program objective: first, without connecting the serial port, verify one round of packing and unpacking.
Below isreal C++ code that can be compiled separately。pack()Generate one frame, then feed this frame to feed() and observe whether the registered function is called. In the Serial_Pack/ root directory, create a new protocol_demo.cpp:
#include <wire_protocol/protocol.hpp>
#include <cstdint>
#include <iostream>
void on_mode(std::uint32_t seq, std::int32_t mode)
{
std::cout << "收到 mode:seq=" << seq << " mode=" << mode << '\n';
}
int main()
{
wire_protocol::CallbackProtocol protocol;
// 0x02 命令收到后,按 on_mode 的参数类型解包。
if (!protocol.set_unpack_callback(0x02, on_mode))
{
std::cerr << "注册命令失败\n";
return 1;
}
const std::uint32_t seq = 1;
const std::int32_t mode = 2;
const auto frame = protocol.pack(0x02, seq, mode);
protocol.feed(frame);
}
Compile and run in the repository root directory (requires a compiler supporting C++20):
cd ~/Serial_Pack
g++ -std=c++20 \
-I example/ros2_ws/src/wire_protocol/include \
protocol_demo.cpp \
example/ros2_ws/src/wire_protocol/src/protocol.cpp \
-o protocol_demo
./protocol_demo
Expected output:
收到 mode:seq=1 mode=2
Here, the feed(frame) is for practicing the protocol API first. When actually connecting to the serial port, what is passed to feed() is the byte fragment received by the serial port each time, it is not required to be exactly a complete frame.
5.2.Key Function Description
5.2.1.CallbackProtocol::set_unpack_callback()
Function prototype (has two calling forms):
template <typename Callable>
bool set_unpack_callback(std::uint8_t command, Callable&& callback) noexcept;
template <typename Method, typename Object>
bool set_unpack_callback(
std::uint8_t command, Method method, Object* object) noexcept;
Purpose: before starting feed(), register a handler function for a command after unpacking. When a valid frame of this command is received, the protocol extracts fields according to the parameter types of the handler function and calls it.
Parameters:
command:std::uint8_t, command number, e.g.0x02.callback:A regular function, function pointer, or callable object that meets the restrictions. It must returnvoid, and the field arguments must be passed by value with explicit types, e.g.void on_mode(std::uint32_t seq, std::int32_t mode).method:When using the member function form, pass a member function pointer, e.g.&Serial_Node::handle_set_mode.object:When using the member function form, pass a pointer to the owning object, e.g.this; the object must remain valid during reception.
返回值:bool。注册成功返回 true;命令重复、8 个回调槽位已满,或传入空函数/对象指针时返回 false。不受支持的 handler 签名会在编译期报错。这里直接传函数或成员函数指针,不用 std::bind 包装协议 handler。
5.2.2.CallbackProtocol::pack()
Function prototype:
template <WireField... T>
auto pack(std::uint8_t command, const T&... fields) const noexcept;
Function: Package the command number and fields into a frame of bytes that can be sent via the serial port.
Parameters:
command:std::uint8_t,the command number to send.fields...:field list, the type is deduced from the template parameterT...; the type and order must be consistent with the handler function on the receiving side. In this example,pack(0x02, seq, mode)corresponds tovoid on_mode(uint32_t seq, int32_t mode).
Return value: written in source as auto, actual type is std::array<std::uint8_t, N>; the array contains the frame data;N is determined at compile time by the number of bytes occupied by the fields plus 7 bytes of frame overhead. For example, for two 32-bit integers, pack(0x02, seq, mode) returns a 15-byte array. Another example command is 0x01:
std::uint32_t seq = 7;
float vx = 1.0f;
float vy = 0.0f;
float wz = 0.5f;
auto frame = protocol.pack(0x01, seq, vx, vy, wz);
The corresponding receive function signature is void on_cmd_vel(uint32_t seq, float vx, float vy, float wz). Do not write float as double and do not write int32_t as another type with an ambiguous compiler width. Both ends must agree on the same command number, field types, and order.
5.2.3.CallbackProtocol::feed()
Function prototype:
void feed(std::span<const std::uint8_t> bytes);
Function: Hand the bytes received by the serial port in this cycle to the protocol; when a complete and valid frame is encountered, automatically call the registered command handler function. A single call may result in no callback, or it may trigger multiple callbacks.
Parameters:
bytes:std::span<const std::uint8_t>indicates the byte segment received this time. It can be a half frame or contain several frames; it does not need to be assembled into a complete frame first.
Return value:voidA protocol object should be retained for a serial port over the long term; do not re-register callbacks during the reception process.
5.2.4.CallbackProtocol::reset()
Function prototype:
void reset() noexcept;
Purpose: Discard residual bytes that have not yet been fully received, for example, call this when you do not want an old partial frame to affect a new connection after a serial port disconnects; registered handler functions are retained.
Parameters: none.
Return value:void.
5.3.Connect to ROS2 example node
serial_comm.cpp Connect the two libraries; the keyreal codeis:
// Serial_Node 的成员:先声明协议,再声明驱动。
wire_protocol::CallbackProtocol protocol_;
serial_transport::Serial_Config serial_config_;
serial_transport::SerialTransport serial_driver_;
// 构造节点时,先注册协议命令,再启动串口接收。
if (!protocol_.set_unpack_callback(0x01, &Serial_Node::handle_cmd_vel, this))
{
return;
}
if (!protocol_.set_unpack_callback(0x02, &Serial_Node::handle_set_mode, this))
{
return;
}
serial_driver_.start(serial_config_,
std::bind(&Serial_Node::serial_receive_callback, this, std::placeholders::_1));
// 接收回调:只负责把收到的片段交给协议。
void serial_receive_callback(std::span<const std::uint8_t> bytes)
{
protocol_.feed(bytes);
}
// 需要发 0x02 命令时:先打包,再交给驱动。
void send_mode(std::uint32_t seq, std::int32_t mode)
{
auto frame = protocol_.pack(0x02, seq, mode);
serial_driver_.async_write(frame);
}
上面是类成员和构造函数中的使用片段,不是另一个完整节点;完整代码在仓库的 serial_comm.cpp。protocol_ 声明在 serial_driver_ 前面,是为了节点销毁时先停串口,再销毁协议对象。
The two commands of the ready-made example are as follows:
| 命令 | 收发字段 | 示例行为 |
|---|---|---|
0x01 |
uint32_t seq, float vx, float vy, float wz |
模拟速度,PC 周期发送并可接收 |
0x02 |
uint32_t seq, int32_t mode |
模拟模式,PC 周期发送并可接收 |
5.4.Use the same protocol on STM32
Here, directly use the example/stm32_hal/ from the repository; there is no need to find another STM32 project. This directory is not a fully generated complete firmware project:it stores the TEST.ioc、C++ application files and user CMake files; first use CubeMX to generate the HAL, FreeRTOS, and top-level build files.
5.5.Step 1: Use CubeMX to generate an STM32 project
Open example/stm32_hal/TEST.ioc. In CubeMX, check whether the target chip matches your board, then generate code in this directory. For the example's .ioc STM32F103C8Tx, the CMake toolchain, FreeRTOS CMSIS V2, USART1, and tasks named serialTask and ledTask were selected; USART1 TX/RX are PA9/PA10 respectively. If your board's pins are different, adjust them in CubeMX first and then generate.
After generation, the directory should contain files such as Core/ and Drivers/ and top-level CMakeLists.txt; the original applications/, bsp/ and cmake/user/ are retained. In the CubeMX settings, keep USER CODE to avoid losing manual modifications upon future regeneration.
5.6.Step 2: Access C++ to build the file
In the newly generatedtop level CMakeLists.txt , keep CubeMX's original C standard settings, and before project() add:
set(CMAKE_CXX_STANDARD 20 CACHE STRING "C++ language standard")
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS ON)
Find the existing CubeMX subdirectory call, and after itaddthe user directory call:
add_subdirectory(cmake/stm32cubemx) # CubeMX 生成的原有行
add_subdirectory(cmake/user) # 需要新增的行
cmake/user/CMakeLists.txt has already added applications/Src/cpp_interface.cpp、serial.cpp、protocol.cpp and other files to the target and set the required header file directories; therefore, it is necessary to add cmake/user here, and merely setting the C++ standard to 20 is not enough. In the future, if new .cpp are added, they must also be included in the source file list of cmake/user/CMakeLists.txt. For the specific placement of the top-level CMake and precautions during CubeMX regeneration, refer to the README-zh_CN.md in that directory.
5.7.Step 3: In main.c call the C++ entry point
In the generated Core/Src/main.c, place the header file into USER CODE BEGIN Includes, and call it after peripheral initialization cpp_main():
/* USER CODE BEGIN Includes */
#include "cpp_interface.h"
/* USER CODE END Includes */
/* main() 中,MX_USART1_UART_Init() 之后 */
/* USER CODE BEGIN 2 */
cpp_main();
/* USER CODE END 2 */
cpp_interface.h has passed extern "C" expose cpp_main() so the C file can call it directly. In the example, isRTOS is 1:cpp_main() In FreeRTOS mode, it will not enter a bare-metal infinite loop; the serial logic is executed by applications/Src/serial.cpp defined StartSerialTask..ioc The FreeRTOS task with the same name has already been configured in , so there is no need to create another one yourself.
5.8.Step 4: See how the example routine calls the protocol API
On the STM32 side, the applications/Inc/protocol.hpp and the ROS2 side use the same set of protocol interfaces;applications/Src/protocol.cpp has already been compiled in by cmake/user/CMakeLists.txt. Below are the key calls extracted from applications/Src/serial.cpp, which are located in the task, the UART receive complete callback, and the transmit loop, respectively:
wire_protocol::CallbackProtocol protocol_;
std::array<uint8_t, 1> rx_buffer;
// StartSerialTask 中:先注册,再启动串口接收。
if (!protocol_.set_unpack_callback(0x01, cmd_vel_callback) ||
!protocol_.set_unpack_callback(0x02, set_mode_callback))
{
Error_Handler();
}
HAL_UART_Receive_IT(&huart1, rx_buffer.data(), rx_buffer.size());
// HAL_UART_RxCpltCallback 中:收到一个字节就交给协议,再继续接收。
protocol_.feed(rx_buffer);
HAL_UART_Receive_IT(&huart1, rx_buffer.data(), rx_buffer.size());
// StartSerialTask 的循环中:打包 0x01,再用 HAL 串口发送。
auto frame = protocol_.pack(0x01, seq, vx, vy, wz);
HAL_UART_Transmit(&huart1, frame.data(), frame.size(), osWaitForever);
These are usage snippets of different functions in the example routines, not a complete program to be pasted into the same function. After the STM32 side receives 0x01 and 0x02 , the callbacks update cmd_vel and set_mode respectively; it periodically sends 0x01 itself, and does not periodically send back 0x02 . The example's receive callback is called in an interrupt with feed() ; your own business callback should be kept short; if multiple tasks or interrupts access the same protocol object together, the protocol operations should be concentrated into one task.
Finally, build the CubeMX-generated project using the installed ARM toolchain and Ninja. If the CMakePresets.json is generated, you can run it under the example/stm32_hal/:
cmake --preset Debug
cmake --build --preset Debug
Then use your debugger or downloader to flash the generated firmware to the board. When wiring, connect PA9/TX on the board to RX of USB-TTL, and PA10/RX to TX of USB-TTL, with a common ground; set both ends to 115200 8N1, no flow control. On the PC side, replace port with the actual device name, for example /dev/ttyUSB0.
6.编译运行 ROS2 示例,观察收发结果
6.1.Compile
Install ROS2,colcon and the standalone Asio development headers (Ubuntu/Debian package name libasio-dev). The following uses ROS2 humble as an example; if you have installed another distribution, replace humble:
cd ~/Serial_Pack/example/ros2_ws
source /opt/ros/humble/setup.bash
colcon build --packages-select wire_protocol serial_transport serial_comm
source install/setup.bash
6.2.Run with virtual serial port
Keep the previous socat terminal running. Execute separately in two new terminals;each new terminal must enter the workspace and load the environment:
# 终端 2:打开 /tmp/ttyV0
cd ~/Serial_Pack/example/ros2_ws
source /opt/ros/humble/setup.bash
source install/setup.bash
ros2 run serial_comm serial_comm --ros-args -r __node:=serial_a -p port:=/tmp/ttyV0
# 终端 3:打开 /tmp/ttyV1
cd ~/Serial_Pack/example/ros2_ws
source /opt/ros/humble/setup.bash
source install/setup.bash
ros2 run serial_comm serial_comm --ros-args -r __node:=serial_b -p port:=/tmp/ttyV1
When both nodes are running, the serial packets sent by each node will reach the other end. Under normal circumstances, the terminal first displays 串口打开成功, followed by [RX cmd_vel] and [RX set_mode]. The values and timing will vary depending on the operating conditions. At the end, press socat on both nodes and the Ctrl+C terminal.
6.3.Run with a real serial port
After generating, building, and flashing the STM32 firmware according to the steps in example/stm32_hal/, only one node runs on the PC side:
ros2 run serial_comm serial_comm --ros-args -p port:=/dev/ttyUSB0 -p baud_rate:=115200
Change /dev/ttyUSB0 to your own device name; you can also modify serial_comm/config/serial_comm.yaml of port and then use ros2 launch serial_comm serial_comm.launch.py. If colcon build --symlink-install is not used, after modifying the configuration, you need to rebuild so that the configuration in the installation directory will be updated.
The board example program sends 0x01,so the PC should see [RX cmd_vel]. The 0x01 and 0x02 sent by the PC will update the cmd_vel and set_mode on the board side respectively, and can be observed with the debugger; because the board example program does not send 0x02, the PC will not see [RX set_mode] because of this.
6.4.When the expected result is not received
串口打开失败: Check the device name and whether USB-TTL is properly connected, and whether the current user has serial port permissions.- Serial port opened but no protocol callback: Check whether TX/RX is crossed, whether they share a common ground, whether the baud rates at both ends match, and whether the command numbers and field types correspond.
set_unpack_callback()Returnfalse: Check whether the command is duplicated, whether it exceeds 8 callbacks, or whether a null function was passed.
The most important invocation relationship in this section is:ROS2/STM32 Their respective serial drivers are responsible for sending and receiving bytes; both ends use the same wire_protocol responsible for pack() and feed().