CodeTheRobot

C++ Advanced · Lesson 12 of 23

Subscribers

create_subscription, callback signatures, shared-pointer messages and QoS matching.

Estimated time · 60–90 min

Learning goals

What you will understand

  • Explain subscribers in your own words
  • Use it in a small robotics example
  • Verify the result instead of assuming it worked

Understand the idea first

The mental model

A subscriber receives every message published on a topic and calls your callback. The callback takes a const shared pointer to the message, so no copy is made. Publisher and subscriber must use compatible Quality of Service, otherwise no messages arrive.

The callback runs on the executor thread, so it must be short (Phase 6). Store the data and let a timer or another thread do heavy work. Use ros2 topic info -v to check the QoS of each endpoint.

Guided lesson

Work through these steps

  1. 1.

    Read the subscribers example and identify what each line owns or changes.

  2. 2.

    Create a small source file, compile with -std=c++17 and warnings enabled, and run it.

  3. 3.

    Change one input, predict the result before running, then compare the output.

  4. 4.

    Record one compiler or runtime error and explain the correction in your own words.

Worked example

Read it before you run it

class Listener : public rclcpp::Node {
// A node that receives messages.
public:
// Public interface.
  Listener() : Node("listener") {
// Name the node.
    sub_ = create_subscription<std_msgs::msg::String>(
// Create a subscription for String messages...
      "chatter", 10,
// ...on /chatter with queue depth 10...
      [this](const std_msgs::msg::String::SharedPtr msg) {
// ...and run this lambda for each message.
        RCLCPP_INFO(get_logger(), "heard: %s", msg->data.c_str());
// Log the text; %s needs a C string.
      });
// End of the lambda and the call.
  }
// End of the constructor.
private:
// Hidden state.
  rclcpp::Subscription<std_msgs::msg::String>::SharedPtr sub_;
// Keep the subscription alive with the node.
};
// End of the class.

What the example is doing

  1. 1.Read declarations from right to left: identify each value's type, name, and initial value.
  2. 2.Follow the data through each expression before considering syntax shortcuts.
  3. 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.

Watch it run · Messages between nodes

See what this code does

The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.

/topicpublishersubscribersubscribermessages delivered: 0MESSAGES BETWEEN NODES

Demo for Subscribers. Expected result: [INFO] [listener]: heard: count 1

Practice code

Now type it yourself

Copy the starter into your ROS 2 package, replace every TODO, then build with colcon build and run it from a sourced terminal.

// src/listener.cpp
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"

class Listener : public rclcpp::Node {
 public:
  Listener() : Node("listener") {
    // TODO: subscribe to "chatter" (depth 10) and log "heard: <data>" in the callback
  }

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

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

Expected output

[INFO] [listener]: heard: count 1
Stuck? Show the full solution (try it yourself first)
// src/listener.cpp
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"

class Listener : public rclcpp::Node {
 public:
  Listener() : Node("listener") {
    sub_ = create_subscription<std_msgs::msg::String>(
        "chatter", 10, [this](const std_msgs::msg::String::SharedPtr msg) {
          RCLCPP_INFO(get_logger(), "heard: %s", msg->data.c_str());
        });
  }

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

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

Expected result

How you know it worked

  • After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
  • Changing the stated input produces the result you predicted.

Practical exercise

Apply the lesson

Write a subscriber for the Talker's topic that counts messages and warns if none arrive for 2 seconds (use a timer). Test with the talker running, stopped and restarted.

Before you continue

  • The program builds with -std=c++17 and no warnings
  • You can explain the key rule without reading the example
  • The normal and edge cases both have recorded results

If something goes wrong

The compiler reports that a name or type is unknown.

Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.

The program runs but the value is wrong.

Print the inputs and intermediate values, then check conversions, units, and collection order.