Section 10.3 Writing ROS 2 Subscribers & Callback Functions
Event-Driven Callbacks
Unlike publishers, subscribers are event-driven. A subscriber does not poll or wait in a loop. Instead, it registers a callback function with ROS 2.
Whenever a new message arrives on the target topic:
-
ROS 2 catches the incoming message payload.
-
It automatically invokes your callback function, passing the message payload as an argument.
In short: a new message arriving on a topic triggers a ROS 2 middleware interrupt, which in turn invokes your
callback(msg) function directlyβthere is no loop in your own code polling for new data.
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
class SimpleSubscriber(Node):
def __init__(self):
super().__init__('simple_subscriber')
# Create subscriber listening to 'chatter'
self.subscription = self.create_subscription(
String,
'chatter',
self.listener_callback,
10
)
def listener_callback(self, msg):
self.get_logger().info(f'Received: "{msg.data}"')
Subsection 10.3.1 Section 10.3 Interactive Exercises
Subsubsection 10.3.1.1 Exercise 10.3.1: ActiveCode Exercise β Safety Laser Scan Processing
Because Runestone CodeLens standard execution environments run pure Python without ROS dependencies installed, we mock the incoming
sensor_msgs/LaserScan data structure using standard Python classes.
Task: Complete the callback function
laser_scan_callback(msg).
-
Iterate through the array of range measurements in
msg.ranges. -
Extract the minimum distance detected (ignoring readings \(\leq 0.0\) which represent sensor errors).
-
If the minimum valid distance is less than 0.5 meters, flag a safety stop (
EMERGENCY_STOP = True) and print an alert!
You have attempted of activities on this page.
