1、创建工作空间
ros2_workspace cd qhr_ws/src
ros2 pkg create test_moudle --build-type ament_cmake --dependencies rclcpp
目录格式如上图
2、创建订阅者和发布者code
创建发布者节点
在路径:/qhr_ws/src/test_moudle/src 下创建
talker.cpp
的文件,内容如下:
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
using namespace std::chrono_literals;
class Talker : public rclcpp::Node {
public:
Talker() : Node("talker") {
publisher_ = this->create_publisher<std_msgs::msg::String>("topic", 10);
auto publish_msg = [this]() -> void {
auto message = std_msgs::msg::String();
message.data = "Hello, world! " + std::to_string(count_++);
RCLCPP_INFO(this->get_logger(), "Publishing: '%s'", message.data.c_str());
this->publisher_->publish(message);
};
timer_ = this->create_wall_timer(500ms, publish_msg);
}
private:
rclcpp::TimerBase::SharedPtr timer_;
rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_;
size_t count_ = 1;
};
int main(int argc, char * argv[]) {
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<Talker>());
rclcpp::shutdown();
return 0;
}
创建订阅者节点
在同一路径下,创建一个名为 listener.cpp
的文件,内容如下:
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
class Listener : public rclcpp::Node
{
public:
Listener() : Node("listener")
{
subscription_ = this->create_subscription<std_msgs::msg::String>("topic", 10, std::bind(&Listener::topic_callback, this, std::placeholders::_1));
}
private:
void topic_callback(const std_msgs::msg::String::SharedPtr msg) const
{
RCLCPP_INFO(this->get_logger(), "I heard: '%s'", msg->data.c_str());
}
rclcpp::Subscription<std_msgs::msg::String>::SharedPtr subscription_;
};
int main(int argc, char* argv[])
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<Listener>());
rclcpp::shutdown();
return 0;
}
3、修改依赖
package.xml文件确保有:
<buildtool_depend>ament_cmake</buildtool_depend>
<depend>rclcpp</depend>
<depend>std_msgs</depend>
CMakeLists.txt
find_package(ament_cmake REQUIRED)
find_package(rclcpp REQUIRED)
find_package(std_msgs REQUIRED)
add_executable(talker src/talker.cpp)
ament_target_dependencies(talker rclcpp std_msgs)
add_executable(listener src/listener.cpp)
ament_target_dependencies(listener rclcpp std_msgs)
install(TARGETS
talker listener
DESTINATION lib/${PROJECT_NAME})
4、编译执行
qhr_ws 工作空间下执行
colcon build
编译成功后,开两个终端执行
source install/setup.zsh (zsh)
source install/setup.bash (bash)
#发布者
ros2 run test_moudle talker
#订阅者
ros2 run test_moudle listener
结束 再次撒花
标签:std,订阅,msgs,rclcpp,listener,talker,发布者,msg,ROS2 From: https://blog.csdn.net/qhr_1012/article/details/142855515