既然ROS2用的c++14的编译环境, 那么就要有c++14的样子, 不能像写ROS一样随心所欲,变量满天飞.
main程序需要非常简洁
rclcpp::init(argc, argv);
google::AllowCommandLineReparsing();
google::InitGoogleLogging(argv[0]);
google::ParseCommandLineFlags(&argc, &argv, false);
auto myclass = std::make_shared<MyClass>("my_class", config);
rclcpp::spin(myclass);
rclcpp::shutdown();
注意事项:
class MyClass : public rclcpp::Node {
...
}
MyClass(std::string name)
: Node(name) {
public:
MyClass_sub_ =
this->create_subscription<geometry_msgs::msg::PoseStamped>(
"pose", 16,
std::bind(&MyClass::HandlePose, this,
std::placeholders::_1));
...
tracked_pose_pub_ =
this->create_publisher<geometry_msgs::msg::PoseStamped>(
"localization_pose", 10);
...
pub_timer_.start(1000, [this]() { PublishMap(); });
...
sync_thread_ = std::thread{std::mem_fn(&MyClass::sync_process),this};
};
~MyClass()
{
some_flag_ = false;
if(sync_thread_.joinable())
{
process_stop_ = true;
sync_thread_.join();
}
}
void HandlePose(const geometry_msgs::msg::PoseStamped::ConstSharedPtr msg)
{
...
}
Eigen::Quaterniond setRPY(double roll, double pitch, double yaw) {
double halfYaw = yaw * 0.5;
double halfPitch = pitch * 0.5;
double halfRoll = roll * 0.5;
double cosYaw = cos(halfYaw);
double sinYaw = sin(halfYaw);
double cosPitch = cos(halfPitch);
double sinPitch = sin(halfPitch);
double cosRoll = cos(halfRoll);
double sinRoll = sin(halfRoll);
Eigen::Quaterniond quaterniond;
quaterniond.x() =
sinRoll * cosPitch * cosYaw - cosRoll * sinPitch * sinYaw;
quaterniond.y() =
cosRoll * sinPitch * cosYaw + sinRoll * cosPitch * sinYaw;
quaterniond.z() =
cosRoll * cosPitch * sinYaw - sinRoll * sinPitch * cosYaw;
quaterniond.w() =
cosRoll * cosPitch * cosYaw + sinRoll * sinPitch * sinYaw;
return quaterniond;
}
private:
rclcpp::Publisher<geometry_msgs::msg::PoseStamped>::SharedPtr
tracked_pose_pub_;
...
rclcpp::Subscription<geometry_msgs::msg::PoseStamped>::SharedPtr
pose_sub_;
Eigen::Vector3d current_pose_;
double heading;
以上就是写ROS2 的cpp程序的基本步骤了.