Ask Your Question

ros2 How do I publish exactly one message?

asked 2019-11-18 08:47:15 -0500

jadebeck49 gravatar image

This question is exactly same as but i want to know how to do the same for ROS2

I would like to publish a single message, irrespective of message size. In this case, I would like publish one std_msgs::String message. How do I do that?

edit retag flag offensive close merge delete


You could try to type

ros2 topic pub -h

in a terminal that has ros2 sourced. You will then see all the options. The -1 or --once flag specifies publish one message and exit.

MCornelis gravatar image MCornelis  ( 2019-11-18 10:13:10 -0500 )edit

So for example something like this, publishes "Hello World" once and then stops.

ros2 topic pub /topic std_msgs/String 'data: Hello World' -1

Or is there a specific reason you want to do it from a node, instead of from terminal?

MCornelis gravatar image MCornelis  ( 2019-11-18 10:15:11 -0500 )edit

Actually i wanted to add this in server client model. Whenever a message is received by the server from any client, it will publish that message to a topic.

jadebeck49 gravatar image jadebeck49  ( 2019-11-20 07:20:42 -0500 )edit

1 Answer

Sort by ยป oldest newest most voted

answered 2019-11-20 12:31:57 -0500

duck-development gravatar image

updated 2019-11-20 14:31:51 -0500

You may use this

ros2 topic pub --once /turtle1/cmd_vel geometry_msgs/msg/Twist '{linear: {x: 2.0, y: 0.0, z: 0.0}, angular: {x: 0.0, y: 0.0, z: 1.8}}'

Or in python

from time import sleep

import rclpy

from std_msgs.msg import String

def main(args=None):

  node = rclpy.create_node('minimal_publisher')

  publisher = node.create_publisher(String, 'topic', 10)

  msg = String()
  senden = true
  i = 0
  while rclpy.ok(): = 'Hello World: %d' % i
    i += 1
    #node.get_logger().info('Publishing: "%s"' %
    If send:
        Send= false
    sleep(0.5)  # seconds

# Destroy the node explicitly
# (optional - otherwise it will be done automatically
# when the garbage collector destroys the node object)

if __name__ == '__main__':
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2019-11-18 08:47:15 -0500

Seen: 1,330 times

Last updated: Nov 20 '19