python的代码网上有一堆,c++的没有找到,在此补充一下,实际测试运行好像c++占用cpu要比python低一些
一、头文件包含部分
#include <chrono>
#include <memory>
#include <string>
#include <vector>
#include <thread>
#include <rclcpp/rclcpp.hpp>
#include <sensor_msgs/msg/imu.hpp>
#include <termios.h>
#include <fcntl.h>
#include <unistd.h>
#include <cmath>
#include <array>
这些头文件包含了所需的标准C++库、ROS 2相关库以及串口通信相关的头文件。
二、类定义:IMUDriverNode
class IMUDriverNode : public rclcpp::Node {
public:
IMUDriverNode()
: Node("imu_driver_node") {
// 创建IMU数据发布者
imu_pub_ = this->create_publisher<sensor_msgs::msg::Imu>("imu", 10);
// 声明ROS参数,并从参数服务器获取串口和波特率参数
this->declare_parameter<std::string>("port", "/dev/ttyUSB0");
this->declare_parameter<int>("baud", 115200);
port_ = this->get_parameter("port").as_string();
baud_rate_ = this->get_parameter("baud").as_int();
// 打开串口
serial_fd_ = open_serial_port(port_, baud_rate_);
if (serial_fd_ < 0) {
RCLCPP_ERROR(this->get_logger(), "Failed to open serial port");
rclcpp::shutdown();
return;
}
// 创建驱动线程
driver_thread_ = std::thread(&IMUDriverNode::driver_loop, this);
}
~IMUDriverNode() {
// 在节点析构时关闭串口和等待驱动线程结束
if (serial_fd_ >= 0) {
close(serial_fd_);
}
if (driver_thread_.joinable()) {
driver_thread_.join();
}
}
私有成员变量:
private:
int serial_fd_;
std::string port_;
int baud_rate_;
std::thread driver_thread_;
rclcpp::