ROS2: Template to create a subscriber

Aus HSHL Mechatronik
Zur Navigation springen Zur Suche springen


zurück zum Hauptartikel

#!/usr/bin/env python # this specifies the interpreter of this script

# ros-core-library for standard ros2-functionality (this is the one for python)
import rclpy
# use ROS-nodes
from rclpy.node import Node
# to subscribe to /scan of type sensor_msgs/msg/LaserScan
from sensor_msgs.msg import LaserScan
# to access the QoS-attributes of messages
from rclpy.qos import ReliabilityPolicy, QoSProfile


# create a Node "MyNode", that inherits all functionality from "Node"
class MyNode(Node):
    # initialize node
    def __init__(self):
        # call super() in the constructor to initialize the Node object
        super().__init__('SomeNameOfMyNode')

        # subsribe to topic "/scan" of type "sensor_msgs/msg/LaserScan"
        self.laser_scan_data = self.create_subscription(
            LaserScan,
            '/scan',
            self.laser_scan_data_callback,           
            QoSProfile(depth=10, reliability=ReliabilityPolicy.RELIABLE)
            
    # callback for Laser-Scan-Data
    def laser_scan_data_callback(self, msg):
        # do something
        self.get_logger().info("[laser_scan_data_callback]: Hello.")
        self.get_logger().info(msg.data)