8.ROS2 topic communication subscriber

 

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. Subscriber realization

Create a new file [subscriber_demo.py] in the same directory as [publisher_demo.py]

image-20231023174819565

Next edit [subscriber_demo.py] to implement the subscriber function and add the following code:

 

3. Edit configuration file

image-20231023175338754

 

4. Compile workspace

 

5. Run program

The sub-terminal execution is as follows:

image-20231023175852916

As shown in the figure above, the terminal running the subscriber will print the /topic_demo information published by the publisher.