ROS2 C++ Subscriber Publisher 订阅发布例子

2022-05-09 12:40:38 浏览数 (1)

文章目录

  • ROS2 Subscriber Publisher 例子

ROS2 Subscriber Publisher 例子

运行环境

代码语言:javascript复制
Ubuntu 20.04
ROS Foxy
  • sub
代码语言:javascript复制
#include <iostream>
#include <rclcpp/rclcpp.hpp>
#include <std_msgs/msg/string.hpp>

void callback(const std_msgs::msg::String::SharedPtr msg) {
    std::cout << "sub " << msg->data.c_str() << std::endl;
}

int main(int argc, char **argv) {
    std::cout << "Hello, ROS2 Sub!" << std::endl;
    rclcpp::init(argc, argv);
    auto node = rclcpp::Node::make_shared("sub_node");
    auto sub = node->create_subscription<std_msgs::msg::String>("/pub", 1, callback);
    rclcpp::spin(node);
    return 0;
}
  • pub
代码语言:javascript复制
#include <iostream>
#include <rclcpp/rclcpp.hpp>
#include <std_msgs/msg/string.hpp>


int main(int argc, char **argv) {
    std::cout << "Hello, ROS2 Sub!" << std::endl;
    rclcpp::init(argc, argv);
    auto node = rclcpp::Node::make_shared("pub_node");
    auto chatter_pub = node->create_publisher<std_msgs::msg::String>("/pub", 1);
    rclcpp::WallRate r(5);
    
    std_msgs::msg::String msg;
    int i = 0;
    while (rclcpp::ok()) {
        msg.data = "data: "   std::to_string(i  );
        std::cout << "pub " << msg.data.c_str() << std::endl;
        chatter_pub->publish(msg);
        rclcpp::spin_some(node);
        r.sleep();
    }
    rclcpp::shutdown();
    return 0;
}
  • CMakeLists.txt
代码语言:javascript复制
cmake_minimum_required(VERSION 3.5.1)
project(ros2_pubsub_demo)

set(CMAKE_CXX_STANDARD 14)
set(TARGET_NAME ${PROJECT_NAME})

find_package(ament_cmake REQUIRED)
find_package(rclcpp REQUIRED)

include_directories(
    ${rclcpp_INCLUDE_DIRS}
)

add_executable(pub pub.cc)
add_executable(sub sub.cc)

ament_target_dependencies(pub rclcpp std_msgs)
ament_target_dependencies(sub rclcpp std_msgs)
  • 运行
代码语言:javascript复制
mkdir build && cd build
cmake ..
make 
./pub
./sub
txt

0 人点赞