ros2 创建发布者订阅者 C++

ROS2 C++发布者订阅者创建
#include <chrono>
#include <memory>
#include <string>

#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"

using namespace std::chrono_literals;

/* This example creates a subclass of Node and uses a fancy C++11 lambda
* function to shorten the callback syntax, at the expense of making the
* code somewhat more difficult to understand at first glance. */

class MinimalPublisher : public rclcpp::Node
{
public:
  MinimalPublisher()
  : Node("minimal_publisher"), count_(0)
  {
    publisher_ = this->create_publisher<std_msgs::msg::String>("topic", 10);
    auto timer_callback =
      [this]() -> void {
        auto message = std_msgs::msg::String();
        message.data = "Hello, world! " + std::to_string(this->count_++);
        RCLCPP_INFO(this->get_logger(), "Publishing: '%s'", message.data.c_str());
        this->publisher_->publish(message);
      };
    timer_ = this->create_wall_timer(500ms, timer_callback);
  }

private:
  rclcpp::TimerBase::SharedPtr timer_;
  rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_;
  size_t count_;
};

int main(int argc, char * argv[])
{
  rclcpp::init(argc, argv);
  rclcpp::spin(std::make_shared<MinimalPublisher>());
  rclcpp::shutdown();
  return 0;
}
# CMakelist
cmake_minimum_required(VERSION 3.5)
project(cpp_pubsub)

# Default to C++14
if(NOT CMAKE_CXX_STANDARD)
  set(CMAKE_CXX_STANDARD 14)
endif()

if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
  add_compile_options(-Wall -Wextra -Wpedantic)
endif()

find_package(ament_cmake REQUIRED)
find_package(rclcpp REQUIRED)
find_package(std_msgs REQUIRED)

add_executable(talker src/publisher_lambda_function.cpp)
ament_target_dependencies(talker rclcpp std_msgs)

install(TARGETS
  talker
  DESTINATION lib/${PROJECT_NAME})

ament_package()
#include <memory>

#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"

class MinimalSubscriber : public rclcpp::Node
{
public:
  MinimalSubscriber()
  : Node("minimal_subscriber")
  {
    auto topic_callback =
      [this](std_msgs::msg::String::UniquePtr msg) -> void {
        RCLCPP_INFO(this->get_logger(), "I heard: '%s'", msg->data.c_str());
      };
    subscription_ =
      this->create_subscription<std_msgs::msg::String>("topic", 10, topic_callback);
  }

private:
  rclcpp::Subscription<std_msgs::msg::String>::SharedPtr subscription_;
};

int main(int argc, char * argv[])
{
  rclcpp::init(argc, argv);
  rclcpp::spin(std::make_shared<MinimalSubscriber>());
  rclcpp::shutdown();
  return 0;
}

ROS 2中使用C++实现发布者订阅者节点是机器人开发中的基础任务。以下是一个完整的示例,展示了如何创建发布者订阅者,并进行话题通信。 ### 发布者节点 发布者节点将定期向指定的话题发布消息。以下是一个C++实现的发布者节点示例: ```cpp #include "rclcpp/rclcpp.hpp" #include "std_msgs/msg/string.hpp" class MinimalPublisher : public rclcpp::Node { public: MinimalPublisher() : Node("minimal_publisher"), count_(0) { // 创建发布者,话题名为"topic",队列长度为10 publisher_ = this->create_publisher<std_msgs::msg::String>("topic", 10); // 设置定时器,每500毫秒发布一次消息 timer_ = this->create_wall_timer( std::chrono::milliseconds(500), [this]() { this->timer_callback(); }); } private: void timer_callback() { // 创建消息并填充数据 auto message = std_msgs::msg::String(); message.data = "Hello, World! " + std::to_string(count_++); // 发布消息 publisher_->publish(message); } rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_; rclcpp::TimerBase::SharedPtr timer_; size_t count_; }; int main(int argc, char *argv[]) { // 初始化ROS 2节点 rclcpp::init(argc, argv); // 启动发布者节点 rclcpp::spin(std::make_shared<MinimalPublisher>()); // 关闭ROS 2节点 rclcpp::shutdown(); return 0; } ``` ### 订阅者节点 订阅者节点会监听指定话题,并在收到消息时打印出来。以下是一个C++实现的订阅者节点示例: ```cpp #include "rclcpp/rclcpp.hpp" #include "std_msgs/msg/string.hpp" class MinimalSubscriber : public rclcpp::Node { public: MinimalSubscriber() : Node("minimal_subscriber") { // 创建订阅者,订阅话题名为"topic" subscription_ = this->create_subscription<std_msgs::msg::String>( "topic", 10, [this](const std_msgs::msg::String::SharedPtr msg) { // 收到消息时打印内容 RCLCPP_INFO(this->get_logger(), "I heard: '%s'", msg->data.c_str()); }); } private: rclcpp::Subscription<std_msgs::msg::String>::SharedPtr subscription_; }; int main(int argc, char *argv[]) { // 初始化ROS 2节点 rclcpp::init(argc, argv); // 启动订阅者节点 rclcpp::spin(std::make_shared<MinimalSubscriber>()); // 关闭ROS 2节点 rclcpp::shutdown(); return 0; } ``` ### 编译与运行 1. **创建ROS 2工作空间** 进入`src`目录并创建ROS 2功能包: ```bash cd ~/ros2_ws/src ros2 pkg create --build-type ament_cmake cpp_pubsub ``` 2. **将上述代码保存为文件** 将发布者代码保存为`minimal_publisher.cpp`,订阅者代码保存为`minimal_subscriber.cpp`。 3. **修改`CMakeLists.txt`** 在`CMakeLists.txt`中添加编译目标: ```cmake add_executable(minimal_publisher src/minimal_publisher.cpp) target_link_libraries(minimal_publisher PRIVATE rclcpp) install(TARGETS minimal_publisher DESTINATION bin) add_executable(minimal_subscriber src/minimal_subscriber.cpp) target_link_libraries(minimal_subscriber PRIVATE rclcpp) install(TARGETS minimal_subscriber DESTINATION bin) ``` 4. **编译功能包** 返回工作空间根目录并编译: ```bash cd ~/ros2_ws colcon build --packages-select cpp_pubsub source install/setup.bash ``` 5. **运行节点** 启动发布者订阅者节点: ```bash ros2 run cpp_pubsub minimal_publisher ros2 run cpp_pubsub minimal_subscriber ``` 通过以上步骤,您可以实现一个简单的ROS 2发布者订阅者系统。发布者每隔500毫秒发布一条消息,而订阅者会接收到这些消息并打印出来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值