1. 创建package

  1. ros2 pkg create --build-type ament_python py_pubsub

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

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

2. 编写publisher节点代码

2.1 编写代码

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

class PyPublisher(Node): def init(self): super(PyPublisher, self).init(‘py_publisher’) self.publisher = self.create_publisher(String, ‘py_topic’, 10) timer_period = 0.5 # seconds self.timer = self.create_timer(timer_period, self.timer_callback) self.i = 0

  1. def timer_callback(self):
  2. msg = String()
  3. msg.data = 'Hello World: %d' % self.i
  4. self.publisher.publish(msg)
  5. self.get_logger().info('Publishing: "%s"' % msg.data)
  6. self.i += 1

def main(): rclpy.init() node = PyPublisher() rclpy.spin(node) node.destroynode() rclpy.shutdown() if name == ‘_main‘: main()

  1. <a name="jq3yV"></a>
  2. ## 2.2 添加依赖
  3. 1. 打开package.xml文件,添加下面两行
  4. ```xml
  5. <exec_depend>rclpy</exec_depend>
  6. <exec_depend>std_msgs</exec_depend>
  1. 打开 setup.py,保证如下字段和package.xml中相同

    1. maintainer='YourName',
    2. maintainer_email='you@email.com',
    3. description='Examples of minimal publisher/subscriber using rclpy',
    4. license='Apache License 2.0',
  2. setup.py中console_scripts在字段的括号内添加以下行entry_points

    1. entry_points={
    2. 'console_scripts': [
    3. 'talker = py_pubsub.publisher:main',
    4. ],
    5. },

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

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

    1. colcon build

    4. 使构建生效

    1. source install/setup.bash

    5. 运行发布节点

    1. ros2 run py_pubsub talker