< >
Home » ROS2与Python入门教程 » ros2与Python入门教程-使用消息

ros2与Python入门教程-使用消息

**ros2与Python入门教程-使用消息 **

说明:

  • 介绍如何python来测试消息

步骤:

cd ~/dev_ws/src/py_pubsub/py_pubsub
vim  publisher_member_function_num.py
  • 内容如下
import rclpy
from rclpy.node import Node

from tutorial_interfaces.msg import Num    # CHANGE


class MinimalPublisher(Node):

    def __init__(self):
        super().__init__('minimal_publisher')
        self.publisher_ = self.create_publisher(Num, 'topic', 10)     # CHANGE
        timer_period = 0.5
        self.timer = self.create_timer(timer_period, self.timer_callback)
        self.i = 0

    def timer_callback(self):
        msg = Num()                                           # CHANGE
        msg.num = self.i                                      # CHANGE
        self.publisher_.publish(msg)
        self.get_logger().info('Publishing: "%d"' % msg.num)  # CHANGE
        self.i += 1


def main(args=None):
    rclpy.init(args=args)

    minimal_publisher = MinimalPublisher()

    rclpy.spin(minimal_publisher)

    minimal_publisher.destroy_node()
    rclpy.shutdown()


if __name__ == '__main__':
    main()
  • 新建文件
cd ~/dev_ws/src/py_pubsub/py_pubsub
vim subscriber_member_function_num.py
  • 内容如下:
import rclpy
from rclpy.node import Node

from tutorial_interfaces.msg import Num        # CHANGE


class MinimalSubscriber(Node):

    def __init__(self):
        super().__init__('minimal_subscriber')
        self.subscription = self.create_subscription(
            Num,                                              # CHANGE
            'topic',
            self.listener_callback,
            10)
        self.subscription

    def listener_callback(self, msg):
            self.get_logger().info('I heard: "%d"' % msg.num) # CHANGE


def main(args=None):
    rclpy.init(args=args)

    minimal_subscriber = MinimalSubscriber()

    rclpy.spin(minimal_subscriber)

    minimal_subscriber.destroy_node()
    rclpy.shutdown()


if __name__ == '__main__':
    main()
  • 变更package.xml,增加
<exec_depend>tutorial_interfaces</exec_depend>
  • 变更setup.py,增加入口
entry_points={
        'console_scripts': [
                'talker_num = py_pubsub.publisher_member_function_num:main',
                'listener_num = py_pubsub.subscriber_member_function_num:main',
        ],
},
  • 安装依赖
rosdep install -i --from-path src --rosdistro foxy -y
  • 编译
colcon build --packages-select py_pubsub
  • 新开终端,运行
. install/setup.bash
ros2 run py_pubsub talker_num
  • 新开终端,运行
. install/setup.bash
ros2 run py_pubsub listener_num

纠错,疑问,交流: 请进入讨论区点击加入Q群

获取最新文章: 扫一扫右上角的二维码加入“创客智造”公众号


标签: ros2与python入门教程