ROS 2 Intro - Topics

Implement a C++ ROS 2 node that subscribes to a topic

  1. In the left-side 'EXPLORER' panel, open the m02_subscriber_cpp.cpp file.

    Left-click hadabot_ws src m02_pkg_cpp src m02_subscriber_cpp.cpp

  2. In the code block class MySubscriberNode : public rclcpp::Node, replace:

      MySubscriberNode()
          : Node("intro_ros2_topic_subscriber_cpp")
      {
        RCLCPP_INFO(this->get_logger(), "C++ node waiting for a ROS 2 message...");
    
        // Add subscriber code here
      }

    ...and type out the following code block1:

      MySubscriberNode()
          : Node("intro_ros2_topic_subscriber_cpp")
      {
        RCLCPP_INFO(this->get_logger(), "C++ node waiting for a ROS 2 message...");
    
        subscription_ = this->create_subscription<std_msgs::msg::String>(
            "my_sub_topic", 10, std::bind(&MySubscriberNode::topic_callback, this, _1));
      }

Run the C++ ROS 2 Node

  1. In the 'Terminal' panel at the bottom of your VSCode, confirm you are at the hadabot_ws directory.

    Then type1:

    $ colcon build

  2. Confirm there are no build errors, then type1,2:

    $ source install/setup.bash
    $ ros2 run m02_pkg_cpp m02_subscriber_cpp

Confirm: If you don't see any error messages, then we're all good!

If the program doesn't run or if there is an error, double check your code. If totally baffled, feel free to reach out to us for help.

Keep the node running (do NOT 'CTRL-C').

Move on to the next step (where we'll publish a message for this node to receive).


1 We highly encourage you to type the code and commands manually, despite being able to easily cut-n-paste, since it helps with learning and understanding the code syntax.
2 Recall from past lesson modules that this source install/setup.bash command sets up the ROS overlay system environment to work on hadabot_ws workspace 'stuff'.