跳转至

topic通信subscriber-python

topic通信subscriber

实现subscriber

1. 创建package(创建过可以省略)

ros2 pkg create --build-type ament_python py_pubsub

可以修改package.xml文件如下信息

<description>C++ client server tutorial</description>
<maintainer email="you@email.com">Your Name</maintainer>
<license>Apache License 2.0</license>

2. 编写publisher节点代码

2.1 下载示例代码

  1. 在package的py_pubsub下创建subscriber.py文件,代码如下
import rclpy
from rclpy.node import Node
from std_msgs.msg import String

class SubNode(Node):
    def __init__(self):
        super(SubNode, self).__init__('py_sub')
        self.create_subscription(String,'py_topic',self.call_back,10)

    def call_back(self,msg):
        self.get_logger().info(msg.data)

def main():
    rclpy.init()
    node = SubNode()
    rclpy.spin(node)
    node.destroy_node()
    rclpy.shutdown()


if __name__ == '__main__':
    main()

2.2 添加依赖

  1. 打开package.xml文件,添加下面两行
<depend>rclpy</depend>
<depend>std_msgs</depend>
  1. 打开 setup.py,确保如下内容和package.xml中一致
maintainer='YourName',
maintainer_email='you@email.com',
description='Examples of minimal publisher/subscriber using rclpy',
license='Apache License 2.0',
  1. setup.pyconsole_scripts在字段的括号内添加以下行entry_points
entry_points={
        'console_scripts': [
            'talker = py_pubsub.publisher:main',
            'subscriber = py_pubsub.subscriber:main',
        ],
},

注意py_pubsub是包名 publisher是py文件名 main是执行的函数

3. 回到工程目录,编译代码

colcon build

4. 使构建生效

source install/setup.bash

5. 运行发布节点

ros2 run py_pubsub subscriber