CodeTheRobot

ROS 2 Lyrical Luth · Lesson 07 of 86

Topics: publishers and subscribers

Streaming typed data, timers, callbacks and inspecting topics from the CLI.

Estimated time · 60–90 min

Learning goals

What you will understand

  • Explain topics: publishers and 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 topic is a named stream of typed messages. Any number of publishers can write to it and any number of subscribers can read it, without knowing each other. It is the right pattern for continuous data such as sensor readings and robot state.

In C++ a publisher is created with create_publisher<MsgT>(topic, qos) and a subscriber with create_subscription<MsgT>(topic, qos, callback). Inspect them with ros2 topic list -t, ros2 topic echo, ros2 topic hz and ros2 topic info.

Guided lesson

Work through these steps

  1. 1.

    Source the ROS 2 Lyrical environment in a fresh terminal.

  2. 2.

    Read the topics: publishers and subscribers example and identify what each line does.

  3. 3.

    Build only the affected package, source the workspace overlay, and run the example.

  4. 4.

    Inspect the result from a second terminal with the ros2 CLI or RViz2 and compare it with the expected result.

Worked example

Read it before you run it

pub_ = create_publisher<std_msgs::msg::Float64>("temperature", 10);
// Create a publisher of Float64 messages on /temperature with a queue depth of 10.
timer_ = create_wall_timer(std::chrono::milliseconds(500), [this] {
// Run the lambda every 500 ms.
  std_msgs::msg::Float64 msg;
// Create an empty message.
  msg.data = 21.5;
// Fill in the value.
  pub_->publish(msg);
// Send it to every subscriber.
});
// End of the timer callback.
sub_ = create_subscription<std_msgs::msg::Float64>("temperature", 10,
// Subscribe to the same topic...
  [this](const std_msgs::msg::Float64::SharedPtr msg) { RCLCPP_INFO(get_logger(), "got %.1f", msg->data); });
// ...and log every value received.

What the example is doing

  1. 1.The ros2 commands query the running graph; they do not prove that a node's internal behavior is correct.
  2. 2.Build from the workspace root, then source install/setup.bash so the shell can discover the new package.
  3. 3.Use a second sourced terminal to inspect nodes and interfaces while the example runs.

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 Topics: publishers and subscribers. Expected result: [INFO] [listener]: got 21.5

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.

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

class Listener : public rclcpp::Node {
 public:
  Listener() : Node("listener") {
    // TODO: subscribe to "temperature" (depth 10) and log "got <value>"
  }

 private:
  rclcpp::Subscription<std_msgs::msg::Float64>::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]: got 21.5
Stuck? Show the full solution (try it yourself first)
// robot_nodes/src/listener.cpp
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/float64.hpp"

class Listener : public rclcpp::Node {
 public:
  Listener() : Node("listener") {
    sub_ = create_subscription<std_msgs::msg::Float64>(
        "temperature", 10, [this](const std_msgs::msg::Float64::SharedPtr msg) {
          RCLCPP_INFO(get_logger(), "got %.1f", msg->data);
        });
  }

 private:
  rclcpp::Subscription<std_msgs::msg::Float64>::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

  • ROS_DISTRO is lyrical in every terminal used for the exercise.
  • The complete package from the exercise builds and the expected graph entity appears in a second terminal.

Practical exercise

Apply the lesson

Write a publisher that sends a counter at 2 Hz and a subscriber that logs it. Use ros2 topic hz to verify the rate, ros2 topic echo to see values, and ros2 topic info -v to read the QoS of both ends.

Before you continue

  • ROS_DISTRO reports lyrical in every terminal you used
  • The example builds and runs without errors
  • You checked the result with a ros2 command, RViz2 or a test, not just by reading the code

If something goes wrong

ros2 cannot find a package or executable.

Source /opt/ros/lyrical/setup.bash, build from the workspace root, then source install/setup.bash in that terminal.

Nodes run but cannot discover each other.

Confirm both terminals use Lyrical, the same ROS_DOMAIN_ID, and compatible network/discovery settings.