yahboom
HomeLearn
Solution
Blog
Online Store
About Us
EN/中文
Raspberry Pi 4B📖
1.Preparation before use
  • 1.1 Download image
  • 1.2 Write image into SD card
  • 1.3 Start up Raspberry Pi
  • 1.4 Linux common commands
  • 1.5 Precautions
2.Basic course
  • 2.1 Log into Raspberry Pi system
  • 2.2 Change password and root account
  • 2.3 Remote transfer file
  • 2.4 Backup image file
  • 2.5 Fixing Raspberry Pi IP
  • 2.6 Set screen keep on
  • 2.7 Get Pi temperature
  • 2.8 Connect WIFI
  • 2.9 Modify Pi time
  • 2.10 Set the boot self-starting program
3.Expand course
  • 3.1 Serial port communicates with external devices
  • 3.2 2.Serial port login Pi
  • 3.3 Configured as a router
  • 3.4 Install Jupyter Lab
  • 3.5 Install Jupyter Widgets
  • 3.6 More Detail for Widgets
  • 3.7 Install OpenCV
  • 3.8 Install Tensorflow
4.Programming course
C language
  • 1.Development environment
  • 2.Print Hello World
  • 3.Pin output level
  • 4.Read pin level
  • 5.PWM output
Python language
  • 1.Development environment
  • 2.Print basic usage
  • 3.Pin output level
  • 4.Read pin level
  • 5.PWM output
5.AI vision course
A.Getting started with OpenCV
  • 6.Picture Rotation
  • 1.Introduction of OpenCV
  • 2.OpenCV image read and display
  • 3.OpenCV image write
  • 4.OpenCV image quality
  • 5.OpenCV pixel operation
B.OpenCV Geometric transformat
  • 1.Picture Zoom
  • 2.Picture Cut
  • 3.Picture Shift
  • 4.Picture Mirroring
  • 5.Affine Map
  • 7.Perspective Transformation
C.OpenCV picture processing
  • 1.Grayscale processing
  • 2.Image Binarization
  • 3.Edge detection
  • 4.Drawing line segment
  • 5.Drawing rectangle circle
  • 6.Drawing text picture
D.OpenCV image beautification
  • 1.Histogram of color pictures
  • 2.Histogram equalization
  • 3.Image restoration
  • 4.Brightness enhancement
  • 5.Skin whitening
  • 6.Gaussian mean filtering
  • 7.Median filtering
F.AI Advanced Course (Ubuntu system)
  • 1. QR code
  • 2. Human posture estimation
  • 3. Target detection
  • 4. Mediapipe development
  • 5. yolov4-tiny
E.Install TensorFlow
  • Install TensorFlow
6.ROS1 coursenew
Basic Course
  • 1.ROS introduction
  • 2.Project file structure
  • 3.Common commands and tools
  • 4.Publisher
  • 5.Subscribers
  • 6.Customize topic messages and use
  • 7.Client
  • 8.Server
  • 9.Custom service messages and usage
  • 10.TF release and monitoring
Visual Image Processing
  • 1. AR vision
  • 2. AR QR code
  • 3. ROS+Opencv foundation
  • 4. ROS+Opencv application
  • 5. MediaPipe development
7.ROS2 coursenew
Docker Course
  • 1.Overview and installation
  • 2.Common commands
  • 3.Understand and publish images
  • 4.Hardware interaction data processing
  • 5.Enter docker container
  • 6.Update docker images
Basic Course
  • 1.Introduction to ROS2
  • 2.Commands and tools
  • 3.ROS2 Topic communications
  • 4.ROS2 service communications
  • 5.ROS2launch file starts
OpenCV Course
  • 1.OpenCV Basic Course
  • 2.ROS+opencv application
  • 3.QR code recognition
  • 4.AR Vision
  • 5.Mediapipe
8.Accessories installation
  • 1. Installation of heat sink
  • 2. Wiring of cooling fan
  • 3. Double fan armor case Installation
  • 4. Argon NEO aluminum case installation
  • 5. Argon ONE aluminum alloy case installation
  • 6. Metal shell with built-in fan installation
  • 7. Acrylic case with cooling fan installation
  • 8. White-red ABS protective case installation
Download
  • Tools
  • C_code
  • Python code
  • ROS System
Download ZIP

Welcome to Raspberry Pi 4B repository

3.ROS2 Topic communications

ROS2 Topic communications

Topic communication is one of the most frequently used communication methods in ROS2, topic communication is based on the publish-subscribe model, there are publishers publishing data on a specified topic, subscribers as long as they subscribe to the data of the topic, they can receive data. Next, let's explain how to use the Python language to achieve topic communication between nodes.

1、Create a new workspace

terminal input:

mkdir -p ros2_ws/src
cd ros2_ws/src

ros2_ws is the name of the workspace, and src is the directory where the feature packs are stored.

2、Create a new feature pack

terminal input:

xxxxxxxxxx
cd ~/ros2_ws/src
ros2 pkg create --build-type ament_python topic_pkg

image-20230428145702547

Switch to topic_pkg folder, there are the following files and folders, the python program we wrote is placed under the topic_pkg folder under this directory, that is:

xxxxxxxxxx
~/ros2_ws/src/topic_pkg/topic_pkg

3、Write the publisher python file

3.1、Program source code

Create a new file, named publisher_demo.py:

xxxxxxxxxx
cd ~/ros2_ws/src/topic_pkg/topic_pkg
gedit publisher_demo.py

Copy the following sections into the file:

xxxxxxxxxx
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
class Topic_Pub(Node):
    def __init__(self,name):
        super().__init__(name)
        self.pub = self.create_publisher(String,"/topic_demo",1)
        self.timer = self.create_timer(1,self.pub_msg)
        
    def pub_msg(self):
        msg = String()
        msg.data = "Hi,I send a message."
        self.pub.publish(msg)
    
def main():
    rclpy.init()
    pub_demo = Topic_Pub("publisher_node")
    rclpy.spin(pub_demo)

This is achieved with the idea of modularity, which is conducive to porting and modifying the code. First define a class, the class name is Topic_Pub, there are two parts in it, one is init and the other is pub_msg. init is the initialization of the class itself, pub_msg the methods of the class, that is, as long as we create the objects of this class, we can use the variables and methods inside.

xxxxxxxxxx
#Import the RCpy library
import rclpy
from rclpy.node import Node
#Import a String message
from std_msgs.msg import String 
#Create a Topic_Pub node subclass that inherits from the Node base class and pass in a parameter name
def __init__(self,name):
        super().__init__(name)
        #Create a publisher with create_publisher function and pass in the following parameters:
        #Topic data type, thread name, queue length to save messages
        self.pub = self.create_publisher(String,"/topic_demo",1) 
        #Create a timer and enter the interrupt handler at intervals of 1s, passing in the following parameters:
        #The interval between execution of the interrupt function, interrupt the handler
        self.timer = self.create_timer(1,self.pub_msg)
#Defines interrupt handlers
def pub_msg(self):
        msg = String()  #Create a variable of type String msg
        msg.data = "Hi,I send a message." #Assign a value to the data in MSG
        self.pub.publish(msg) #Publish topic data
        
#Main function
def main():
    rclpy.init() #initialize
    pub_demo = Topic_Pub("publisher_node") 
    #To create a Topic_Pub class object, the parameter passed in is the name of the node
    rclpy.spin(pub_demo) 
    #Execute the rclpy.spin function, pass in a parameter, the parameter is the Topic_Pub class object just created 

3.2、Modify the setup.py file

terminal input:

xxxxxxxxxx
cd ~/ros2_ws/src/topic_pkg
gedit setup.py

Locate the location as shown in the image below:

image-20230428164527355

Add the following to 'console_scripts': []

​x
'publisher_demo = topic_pkg.publisher_demo:main'

Code explanation:

image-20230428164648037

The name of the executable file is our custom, that is, which program we need to execute when ros2 run, the function package name is which function package your python file is located in, followed by the name of the python file, and the last main is the program execution entry. As long as it is a program written in python format, compile and generate executable files, you need to add it here in the above format.

3.3、Compile the workspace

xxxxxxxxxx
cd ~/ros2_ws
colcon build

Compile successfully, enter the following command to add the workspace to the system environment variable,

xxxxxxxxxx
echo "source ~/ros2_ws/install/setup.bash" >> ~/.bashrc

Then, reopen the terminal or refresh the environment variable to take effect.

xxxxxxxxxx
source ./.bashrc

3.4、Run the program

terminal input,

xxxxxxxxxx
ros2 run topic_pkg publisher_demo 

After the program runs successfully, there is no printing anything, we can view the data through the ros2 topic tool, first check whether this topic is published, terminal input,

xxxxxxxxxx
ros2 topic list

image-20230428170044755

This topic_demo is the topic data defined in the program, next, we use ros2 topic echo to print this data, terminal input,

xxxxxxxxxx
ros2 topic echo /topic_demo

image-20230428170548198

As you can see, the terminal prints "Hi, I send a message." msg.data = "Hi,I send a message" in our code." unanimous.

4、Write subscriber python files

4.1、Program source code

Create a new file, named subscriber_demo.py,

xxxxxxxxxx
cd ~/ros2_ws/src/topic_pkg/topic_pkg
gedit subscriber_demo.py

Copy the following sections into the file,

xxxxxxxxxx
#Import the relevant libraries
import rclpy
from rclpy.node import Node
from std_msgs.msg import String

class Topic_Sub(Node):
    def __init__(self,name):
        super().__init__(name)  
        #The create_subscription used to create the subscriber is: topic data type, topic name, callback function name, queue length
        self.sub = self.create_subscription(String,"/topic_demo",self.sub_callback,1) 
    #Callback function executor: prints the received information
    def sub_callback(self,msg):
        print(msg.data)
def main():
    rclpy.init() #ROS2 Python interface initialization
    sub_demo = Topic_Sub("subscriber_node") #Create an object and initialize it
    rclpy.spin(sub_demo)

4.2、Modify the setup.py file

terminal input,

xxxxxxxxxx
cd ~/ros2_ws/src/topic_pkg
gedit setup.py

Locate the location as shown in the image below,

image-20230504092717152

Add the following to 'console_scripts': [] in the format,

xxxxxxxxxx
'subscriber_demo = topic_pkg.subscriber_demo:main'

image-20230504092834784

4.3、Compile the workspace

xxxxxxxxxx
cd ~/ros2_ws
colcon build

After the compilation is completed, refresh the environment variables of the workspace.

xxxxxxxxxx
source ~/ros2_ws/install/setup.bash

4.4、Run the program

terminal input,

xxxxxxxxxx
#Start the publisher node
ros2 run topic_pkg publisher_demo 
#Start the subscriber node
ros2 run topic_pkg subscriber_demo

image-20230504093741770

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

You can use the following command to view the topic communication between the two nodes:

xxxxxxxxxx
ros2 run rqt_graph rqt_graph

image-20230504094102343

5、summary

5.1、Python writes a framework for topic communicators

image-20230504095534969

5.2、Modify the contents of setup.py file

To write a node program using Python, you need to modify the setup.py file, refer to the above content, and add and generate your own node program.

Commands and tools
ROS2 service communications

COMPANY

  • About us
  • Team Style
  • Blog

LEARNING & EXPLORATION

  • Tutorials
  • Edge AI hardware
  • Educational robots
  • Embedded intelligent hardware

WHERE TO BUY

  • Yahboom Online Store
  • Amazon
  • Alibaba
  • AliExpress
  • Mercado

TECHNOLOGY SUPPORT

  • Email: support@yahboom.com

BE A DISTRIBUTOR

  • Email: sales@yahboom.com
QR Code
QR Code

Copyright © 2017-2026 Yahboom. All Rights Reserved.

EN/中文