Back to Module
Ros2
Courses & Resources
Code Demos
ROS2 Publisher/Subscriber
ROS2 基本通信模式:发布者和订阅者节点
python
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, "robot_status", 10)
self.timer = self.create_timer(0.5, self.timer_callback)
self.count = 0
def timer_callback(self):
msg = String()
msg.data = f"Robot status update #{self.count}"
self.publisher.publish(msg)
self.get_logger().info(f"Publishing: {msg.data}")
self.count += 1
def main():
rclpy.init()
publisher = MinimalPublisher()
rclpy.spin(publisher)
publisher.destroy_node()
rclpy.shutdown()
if __name__ == "__main__":
main()