Skip to content

Instantly share code, notes, and snippets.

@rfzeg
Last active May 29, 2023 19:10
Show Gist options
  • Save rfzeg/b392c7d7a3495b04ef218724e73b2df1 to your computer and use it in GitHub Desktop.
Save rfzeg/b392c7d7a3495b04ef218724e73b2df1 to your computer and use it in GitHub Desktop.
ROS2: Retrieve the total number of laser rays using the python interpreter (adjust topic name if neccesary)
import rclpy
from sensor_msgs.msg import LaserScan
from rclpy.qos import ReliabilityPolicy, QoSProfile
def scan_callback(msg):
global g_node
g_node.get_logger().info('Number of rays: "%d"' % len(msg.ranges))
g_node.get_logger().info('Angle of first ray: "%.2f"' % msg.angle_min)
g_node.get_logger().info('Angle of last ray: "%.2f"' % msg.angle_max)
g_node.get_logger().info('Total angular area of coverage: "%.2f"' % (msg.angle_max-msg.angle_min))
g_node = None
global g_node
rclpy.init()
qos_policy = rclpy.qos.QoSProfile(reliability=rclpy.qos.ReliabilityPolicy.BEST_EFFORT,history=rclpy.qos.HistoryPolicy.KEEP_LAST,depth=1)
g_node = rclpy.create_node('minimal_subscriber')
subscription = g_node.create_subscription(LaserScan, '/scan', scan_callback, qos_profile=qos_policy)
if rclpy.ok():
rclpy.spin_once(g_node)
#g_node.destroy_node()
#rclpy.shutdown()
@rfzeg
Copy link
Author

rfzeg commented Dec 21, 2022

Alternatively you can run from the command line:

ros2 topic echo --full-length --once
or:

ros2 topic echo -f --once

Which will output all elements for the ranges arrays. By default the length of arrays gets truncated to 128 elements. (--once option for ros2 humble and above).

example: ros2 topic echo -f --once /scan > scan.txt

@rfzeg
Copy link
Author

rfzeg commented Dec 30, 2022

Alternatively you can consult the data sheet or the gazebo plugin.

@rfzeg
Copy link
Author

rfzeg commented May 29, 2023

ROS1 version:

import rospy
from sensor_msgs.msg import LaserScan

def scan_callback(msg):
  rospy.loginfo('Number of rays: "%d"' % len(msg.ranges))
  rospy.loginfo('Angle of first ray: "%.2f"' % msg.angle_min)
  rospy.loginfo('Angle of last ray: "%.2f"' % msg.angle_max)
  rospy.loginfo('Total angular area of coverage: "%.2f"' % (msg.angle_max - msg.angle_min))

def main():
  rospy.init_node('minimal_subscriber')
  subscription = rospy.Subscriber('/kobuki/laser/scan', LaserScan, scan_callback)
  
  try:
    rospy.spin()
  except KeyboardInterrupt:
    rospy.loginfo("Ctrl+C detected. Stopping the script.")

if __name__ == '__main__':
  main()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment