CodeTheRobot

C++ Advanced · Lesson 11 of 23

Publishers

create_publisher, message types, QoS depth and wall timers.

Estimated time · 60–90 min

Learning goals

What you will understand

  • Explain publishers 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 publisher sends messages of one type to a named topic. create_publisher<MsgT>(topic, qos) returns a shared pointer that you keep as a member, so its lifetime equals the node's. std_msgs::msg::String is a simple standard message.

A wall timer usually drives publishing: create_wall_timer(500ms, callback). The number in the QoS (10) is the queue depth. Check the result with ros2 topic echo and ros2 topic hz.

Guided lesson

Work through these steps

  1. 1.

    Read the publishers 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

#include "std_msgs/msg/string.hpp"
// Generated C++ class for the String message.
using namespace std::chrono_literals;
// Enables the 500ms literal.
class Talker : public rclcpp::Node {
// A node that publishes.
public:
// Public interface.
  Talker() : Node("talker") {
// Name the node.
    pub_ = create_publisher<std_msgs::msg::String>("chatter", 10);
// Create a publisher on /chatter with queue depth 10.
    timer_ = create_wall_timer(500ms, [this] {
// Every 500 ms run this lambda.
      std_msgs::msg::String msg;
// Create an empty message.
      msg.data = "count " + std::to_string(++n_);
// Fill in its data field.
      pub_->publish(msg);
// Send it.
    });
// End of the lambda and timer.
  }
// End of the constructor.
private:
// Hidden state.
  rclcpp::Publisher<std_msgs::msg::String>::SharedPtr pub_;
// Keep the publisher alive as long as the node.
  rclcpp::TimerBase::SharedPtr timer_; int n_{0};
// The timer and a counter.
};
// 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 Publishers. Expected result: ros2 topic echo /chatter -> data: count 1, data: count 2, ...

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/talker.cpp
#include <chrono>
#include <string>

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

using namespace std::chrono_literals;

class Talker : public rclcpp::Node {
 public:
  Talker() : Node("talker") {
    // TODO: create a publisher on "chatter" (depth 10) and a 500 ms wall timer that publishes "count N"
  }

 private:
  rclcpp::Publisher<std_msgs::msg::String>::SharedPtr pub_;
  rclcpp::TimerBase::SharedPtr timer_;
  int n_{0};
};

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

Expected output

ros2 topic echo /chatter  ->  data: count 1, data: count 2, ...
Stuck? Show the full solution (try it yourself first)
// src/talker.cpp
#include <chrono>
#include <string>

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

using namespace std::chrono_literals;

class Talker : public rclcpp::Node {
 public:
  Talker() : Node("talker") {
    pub_ = create_publisher<std_msgs::msg::String>("chatter", 10);
    timer_ = create_wall_timer(500ms, [this] {
      std_msgs::msg::String msg;
      msg.data = "count " + std::to_string(++n_);
      pub_->publish(msg);
    });
  }

 private:
  rclcpp::Publisher<std_msgs::msg::String>::SharedPtr pub_;
  rclcpp::TimerBase::SharedPtr timer_;
  int n_{0};
};

int main(int argc, char** argv) {
  rclcpp::init(argc, argv);
  rclcpp::spin(std::make_shared<Talker>());
  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

Publish a sensor_msgs/msg/Temperature message at 2 Hz. Check the rate with ros2 topic hz, print one message with ros2 topic echo, then change the period to 100 ms and confirm the new rate.

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.