7.ROS2 topic communication publisher

 

1. Introduction to topic communication

Topic communication is the most frequently used communication method in ROS2. A publisher publishes data on a specified topic, and subscribers can receive the data as long as they subscribe to the data on the topic.

Topic communication is based on the publish/subscribe model, as shown in the figure:

image8

The characteristics of topic data transmission are from one node to another node. The object sending data is called Publisher, and the object receiving data is called Subscriber. Each topic needs to have a name, the transmitted data also needs to have a fixed data type.

Next, we will explain how to use Python language to implement topic communication between nodes.

 

This case is located in the factory docker container. The source code location is:

 

2. Create a new function package

After executing the above command, the pkg_topic function package will be created, and a publisher_demo node will be created, and the relevant configuration files have been configured.

image-20231023170921392

 

3. Publisher implementation

Next edit [publisher_demo.py] to implement the publisher’s functions and add the following code:

 

4. Edit configuration file

image-20231023173312172

 

5. Compile workspace

 

6.Run program

Open a terminal:

After the program runs successfully, nothing is printed. We can view the data through the ros2 topic tool. First, check whether there is a topic published, and open another terminal to input:

image-20231023173728019

This topic_demo is the topic data defined in the program. Next, we use ros2 topic echo to print this data, and enter in the terminal:

image-20231023173821223

It can be seen that the "Hi,I send a message." printed by the terminal is consistent with the msg.data = "Hi,I send a message." in our code.