topic通信publisher-python
topic通信publisher¶
实现¶
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
文件,代码如下
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.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
2.2 添加依赖¶
- 打开
package.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