上一篇我们通过C++实现了发布者和订阅者,本篇我们试试用Python来实现同样的功能。
1.创建功能包
首先我们在之前创建的dev_ws工作空间中来创建一个放置节点代码的功能包。
打开一个新的终端,cd到dev_ws/src目录下,然后运行创建功能包的指令:
ros2 pkg create --build-type ament_python py_pubsub
很快就创建好了一个叫做py_pubsub的功能包。
2.创建发布者节点
在py_pubsub/py_pubsub文件夹下,创建一个发布者节点的代码文件publisher_member_function.py,然后拷贝以下代码放进去:
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
class MinimalPublisher(Node):
def __init__(self):
super().__init__('minimal_publisher')
self.publisher_ = self.create_publisher(String, 'topic', 10)
timer_period = 0.5 # seconds
self.timer = self.create_timer(timer_period, self.timer_callback)
self.i = 0
def timer_callback(self):
msg = String()
msg.data = 'Hello World: %d' % self.i
self.publisher_.publish(msg)
self.get_logger().info('Publishing: "%s"' % msg.data)
self.i += 1
def main(args=None):
rclpy.init(args=args)
minimal_publisher = MinimalPublisher()
rclpy.spin(minimal_publisher)
# Destroy the node explicitly
# (optional - otherwise it will be done automatically
# when the garbage collector destroys