Main Content

send

Publish ROS 2 message to topic

Syntax

Description

example

send(pub,msg)publishes a message to the topic specified by the publisher,pub. This message can be received by all subscribers in the ROS 2 network that are subscribed to the topic specified bypub.

Examples

collapse all

The primary mechanism for ROS 2 nodes to exchange data is to send and receivemessages. Messages are transmitted on atopic和每个主题都有一个惟一名称2 netw ROSork. If a node wants to share information, it must use apublisherto send data to a topic. A node that wants to receive that information must use asubscriberfor that same topic. Besides its unique name, each topic also has amessage type, which determines the type of messages that are allowed to be transmitted in the specific topic.

This publisher-subscriber communication has the following characteristics:

  • Topics are used for many-to-many communication. Multiple publishers can send messages to the same topic and multiple subscribers can receive them.

  • Publisher and subscribers are decoupled through topics and can be created and destroyed in any order. A message can be published to a topic even if there are no active subscribers.

This example shows how to publish and subscribe to topics in a ROS 2 network. It also shows how to:

  • Wait until a new message is received, or

  • Use callbacks to process new messages in the background

先决条件:Get Started with ROS 2,Connect to a ROS 2 Network

Subscribe and Wait for Messages

Create a sample ROS 2 network with several publishers and subscribers.

exampleHelperROS2CreateSampleNetwork

Useros2 topic listto see which topics are available.

ros2topiclist
/parameter_events /pose /rosout /scan

Assume you want to subscribe to the/scantopic. Useros2subscriberto subscribe to the/scantopic. Specify the name of the node with the subscriber. If the topic already exists in the ROS 2 network,ros2subscriberdetects its message type automatically, so you do not need to specify it.

detectNode = ros2node("/detection"); pause(2) laserSub = ros2subscriber(detectNode,"/scan"); pause(2)

Usereceiveto wait for a new message. Specify a timeout of 10 seconds. The outputscanDatacontains the received message data.statusindicates whether a message was received successfully andstatustextprovides additional information about thestatus.

[scanData,status,statustext] = receive(laserSub,10);

You can now remove the subscriberlaserSuband the node associated to it.

clearlaserSubcleardetectNode

Subscribe Using Callback Functions

Instead of usingreceiveto get data, you can specify a function to be called when a new message is received. This allows other MATLAB code to execute while the subscriber is waiting for new messages. Callbacks are essential if you want to use multiple subscribers.

Subscribe to the/posetopic, using the callback functionexampleHelperROS2PoseCallback, which takes a received message as the input. One way of sharing data between your main workspace and the callback function is to use global variables. Define two global variablesposandorient.

controlNode = ros2node("/base_station"); poseSub = ros2subscriber(controlNode,"/pose",@exampleHelperROS2PoseCallback);globalposglobalorient

The global variablesposandorientare assigned in theexampleHelperROS2PoseCallbackfunction when new message data is received on the/posetopic.

functionexampleHelperROS2PoseCallback(message)% Declare global variables to store position and orientationglobalposglobalorient% Extract position and orientation from the ROS message and assign the% data to the global variables.pos = [message.linear.x message.linear.y message.linear.z]; orient = [message.angular.x message.angular.y message.angular.z];end

Wait a moment for the network to publish another/posemessage. Display the updated values.

pause(3) disp(pos)
-0.0409 0.0076 0.0183
disp(orient)
0.0047 -0.0074 0.0144

If you type inposandorienta few times in the command line you can see that the values are continuously updated.

Stop the pose subscriber by clearing the subscriber variable

clearposeSubclearcontrolNode

Note: There are other ways to extract information from callback functions besides using globals. For example, you can pass a handle object as additional argument to the callback function. See theCallback Definitiondocumentation for more information about defining callback functions.

发布消息

Create a publisher that sends ROS 2 string messages to the/chattertopic.

chatterPub = ros2publisher(node_1,"/chatter","std_msgs/String");

Create and populate a ROS 2 message to send to the/chattertopic.

chatterMsg = ros2message(chatterPub); chatterMsg.data ='hello world';

Useros2 topic listto verify that the/chattertopic is available in the ROS 2 network.

ros2topiclist
/chatter /parameter_events /pose /rosout /scan

Define a subscriber for the/chattertopic.exampleHelperROS2ChatterCallbackis called when a new message is received, and displays the string content in the message.

chatterSub = ros2subscriber(node_2,"/chatter",@exampleHelperROS2ChatterCallback)
chatterSub = ros2subscriber with properties: TopicName: '/chatter' LatestMessage: [] MessageType: 'std_msgs/String' NewMessageFcn: @exampleHelperROS2ChatterCallback History: 'keeplast' Depth: 10 Reliability: 'reliable' Durability: 'volatile'

Publish a message to the/chattertopic. Observe that the string is displayed by the subscriber callback.

send(chatterPub,chatterMsg) pause(3)
ans = 'hello world'

TheexampleHelperROS2ChatterCallbackfunction was called when the subscriber received the string message.

Disconnect From ROS 2 Network

Remove the sample nodes, publishers and subscribers from the ROS 2 network. Also clear the global variablesposandorient

clearglobalposorientclear

Next Steps

Input Arguments

collapse all

ros2publisherobject, specified as a handle, that publishes the specified topic.

ROS 2 message, specified as a structure, with compatible fields for that message type.

Extended Capabilities

C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.

Version History

Introduced in R2019b