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 编写代码
- 在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
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(): rclpy.init() node = PyPublisher() rclpy.spin(node) node.destroynode() rclpy.shutdown() if name == ‘_main‘: main()
<a name="jq3yV"></a>
## 2.2 添加依赖
1. 打开package.xml文件,添加下面两行
```xml
<exec_depend>rclpy</exec_depend>
<exec_depend>std_msgs</exec_depend>
打开 setup.py,保证如下字段和package.xml中相同
maintainer='YourName',
maintainer_email='you@email.com',
description='Examples of minimal publisher/subscriber using rclpy',
license='Apache License 2.0',
setup.py中console_scripts在字段的括号内添加以下行entry_points
entry_points={
'console_scripts': [
'talker = py_pubsub.publisher:main',
],
},
注意py_pubsub是包名 publisher是py文件名 main是执行的函数
3. 回到工程目录,编译代码
colcon build
4. 使构建生效
source install/setup.bash
5. 运行发布节点
ros2 run py_pubsub talker