CodeTheRobot

ROS 2 Lyrical Luth · Lesson 46 of 86

LiDAR data processing

LaserScan fields, invalid readings, filtering and finding the nearest obstacle.

Estimated time · 45–75 min

Learning goals

What you will understand

  • Explain lidar data processing in your own words
  • Use it in a small robotics example
  • Verify the result instead of assuming it worked

Understand the idea first

The mental model

sensor_msgs/msg/LaserScan holds ranges[] measured at angles angle_min + i·angle_increment, plus range_min and range_max. Readings can be inf (nothing hit), NaN (invalid) or outside [range_min, range_max]; always filter them before use.

A common first task is the nearest obstacle: scan the valid ranges and keep the smallest with its angle. Use it for a simple safety stop. Process the scan quickly in the callback and publish results; do not block.

Guided lesson

Work through these steps

  1. 1.

    Source the ROS 2 Lyrical environment in a fresh terminal.

  2. 2.

    Read the lidar data processing example and identify what each line does.

  3. 3.

    Build only the affected package, source the workspace overlay, and run the example.

  4. 4.

    Inspect the result from a second terminal with the ros2 CLI or RViz2 and compare it with the expected result.

Worked example

Read it before you run it

void on_scan(const sensor_msgs::msg::LaserScan::SharedPtr scan) {
// Callback for every scan.
  float best = scan->range_max; int best_i = -1;
// Start with the maximum range and no index.
  for (size_t i = 0; i < scan->ranges.size(); ++i) {
// Visit every ray.
    float r = scan->ranges[i];
// The measured distance.
    if (!std::isfinite(r) || r < scan->range_min || r > scan->range_max) continue;
// Skip inf, NaN and out-of-range values.
    if (r < best) { best = r; best_i = static_cast<int>(i); }
// Keep the closest valid reading.
  }
// End of the loop.
  if (best_i >= 0) RCLCPP_INFO(get_logger(), "nearest %.2f m at %.2f rad", best, scan->angle_min + best_i * scan->angle_increment);
// Log the distance and its bearing.
}
// End of the callback.

What the example is doing

  1. 1.The ros2 commands query the running graph; they do not prove that a node's internal behavior is correct.
  2. 2.Build from the workspace root, then source install/setup.bash so the shell can discover the new package.
  3. 3.Use a second sourced terminal to inspect nodes and interfaces while the example runs.

Watch it run · Sensor view

See what this code does

The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.

SENSOR VIEW

Demo for LiDAR data processing. Expected result: min=0.8 index=2

Practice code

Now type it yourself

Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice

#include <cmath>
#include <iostream>
#include <limits>
#include <vector>

int main() {
  const float inf = std::numeric_limits<float>::infinity();
  const std::vector<float> ranges{2.5f, inf, 0.8f, 1.6f, std::nanf("")};
  const float range_min = 0.12f, range_max = 10.0f;
  float best = range_max;
  int best_i = -1;
  for (std::size_t i = 0; i < ranges.size(); ++i) {
    // TODO: skip readings that are not finite or outside [range_min, range_max]; keep the smallest valid one and its index
  }
  std::cout << "min=" << best << " index=" << best_i << '\n';
  return 0;
}

Expected output

min=0.8 index=2
Stuck? Show the full solution (try it yourself first)
#include <cmath>
#include <iostream>
#include <limits>
#include <vector>

int main() {
  const float inf = std::numeric_limits<float>::infinity();
  const std::vector<float> ranges{2.5f, inf, 0.8f, 1.6f, std::nanf("")};
  const float range_min = 0.12f, range_max = 10.0f;
  float best = range_max;
  int best_i = -1;
  for (std::size_t i = 0; i < ranges.size(); ++i) {
    const float r = ranges[i];
    if (!std::isfinite(r) || r < range_min || r > range_max) continue;
    if (r < best) {
      best = r;
      best_i = static_cast<int>(i);
    }
  }
  std::cout << "min=" << best << " index=" << best_i << '\n';
  return 0;
}

Expected result

How you know it worked

  • ROS_DISTRO is lyrical in every terminal used for the exercise.
  • The complete package from the exercise builds and the expected graph entity appears in a second terminal.

Practical exercise

Apply the lesson

Write a node that subscribes to /scan, finds the nearest valid obstacle in the front 60 degrees, and publishes zero velocity when it is closer than 0.5 m.

Before you continue

  • ROS_DISTRO reports lyrical in every terminal you used
  • The example builds and runs without errors
  • You checked the result with a ros2 command, RViz2 or a test, not just by reading the code

If something goes wrong

ros2 cannot find a package or executable.

Source /opt/ros/lyrical/setup.bash, build from the workspace root, then source install/setup.bash in that terminal.

Nodes run but cannot discover each other.

Confirm both terminals use Lyrical, the same ROS_DOMAIN_ID, and compatible network/discovery settings.