Skip to content

Week 4 Scan Callback Function

Tom Howard edited this page Jan 13, 2022 · 1 revision

Week 4 ROS Services

Suggested approach for creating a /scan callback function

Based on what you have learnt throughout this course so far, you should now be able to set up a subscriber within your code to subscribe to the /scan topic:

self.subscriber = rospy.Subscriber('/scan', LaserScan, self.scan_callback)

The above assumes that you are using a Python Class structure in your code (which you really should be!), and we also assume that you have already imported the LaserScan message type correctly at the start of your code:

from sensor_msgs.msg import LaserScan

You could then develop a callback function (called scan_callback() in this case) using the approach illustrated below. Note: this also requires the numpy Python library, which would also need to be imported at the start of your code in the following way:

import numpy as np

The scan_callback() could then be developed to obtain (for instance) a 40° arc of LaserScan data ahead of the robot:

def scan_callback(self, scan_data):
    # From the front of the robot, obtain a 20 degree 
    # arc of scan data either side of the x-axis 
    left_arc = scan_data.ranges[0:21]
    right_arc = scan_data.ranges[-20:]
    # combine the "left_arc" and "right_arc" data arrays, flip them so that 
    # the data is arranged from left (-20 degrees) to right (+20 degrees)
    # then convert to a numpy array
    front_arc = np.array(left_arc[::-1] + right_arc[::-1])
    # Obtain the minimum distance measurement within the "front_arc" array
    # to indicate when we are getting close to something up ahead:
    self.min_distance = front_arc.min()

    # Advanced:
    # Create another numpy array which represents the angles 
    # (in degrees) associated with each of the data-points in 
    # the "front_arc" array above:
    arc_angles = np.arange(-20, 21)
    # determine the angle at which the minimum distance value is located
    # in front of the robot:
    self.object_angle = arc_angles[np.argmin(front_arc)]

What we are doing here is illustrated in the figure below:

Clone this wiki locally