1、创建工作空间
首先,在根目录下面创建一个新的工作空间test_w
和新的功能包topic_pkg
,然后新建脚本文件topic_interface_pub.cpp和topic_interface_sub.cpp,然后用VScode打开test_w文件夹。
mkdir -p ./text_w/src
cd text_w/src
ros2 pkg create topic_pkg --build-type ament_cmake --dependencies rclcpp std_msgs --node-name topic_interface_pub
touch ./topic_pkg/src/topic_interface_sub.cpp
2、测试一下简单的话题通信
编写发布者节点,复制下面代码到 topic_interface_pub.cpp
/***
功能:以某个固定频率发布 hello world
***/
#include "rclcpp/rclcpp.hpp" // ROS2 C++接口库
#include "std_msgs/msg/string.hpp" // 字符串消息类型
using namespace std::chrono_literals;//设置持续时间相关
class PublisherNode : public rclcpp::Node
{
public:
PublisherNode(): Node("topic_helloworld_pub") // ROS2节点父类初始化
{
RCLCPP_INFO(this->get_logger(), "Create Publisher Finished !");
// 创建发布者对象(消息类型、话题名、队列长度)
publisher_ = this->create_publisher<std_msgs::msg::String>("chatter", 10);
// 创建一个定时器,定时执行回调函数
timer_ = this->create_wall_timer(500ms, std::bind(&PublisherNode::timer_callback, this));
}
private:
// 创建定时器周期执行的回调函数
void timer_callback()
{
// 创建一个String类型的消息对象
auto mssage = std_msgs::msg::String();
// 填充消息对象中的消息数据
mssage.data = "Hello World " + std::to_string(count++);
// 发布话题消息
RCLCPP_INFO(this->get_logger(), "Publishing: '%s'", mssage.data.c_str());
// 输出日志信息,提示已经完成话题发布
publisher_->publish(mssage);
}
rclcpp::TimerBase::SharedPtr timer_; // 定时器指针
rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_; // 发布者指针
size_t count; // 计数器
};
// ROS2节点主入口main函数
int main(int argc, char * argv[])
{
// ROS2 C++接口初始化
rclcpp::init(argc, argv);
// 创建ROS2节点对象并进行初始化
rclcpp::spin(std::make_shared<PublisherNode>()); //挂起
// 关闭ROS2 C++接口
rclcpp::shutdown();
return 0;
}
编写订阅者节点,复制下面代码到 topic_interface_sub.cpp
/***
功能:订阅发布者发布的 hello world
***/
#include "rclcpp/rclcpp.hpp" // ROS2 C++接口库
#include "std_msgs/msg/string.hpp" // 字符串消息类型
using std::placeholders::_1;
class SubscriberNode : public rclcpp::Node
{
public:
SubscriberNode(): Node("topic_helloworld_s