ROS2机器人激光雷达测距的C++代码
时间: 2023-09-15 15:22:25 浏览: 415
激光雷达资料包,配置环境所需
下面是一个使用ROS2中激光雷达数据进行距离测量的示例代码:
```cpp
#include "rclcpp/rclcpp.hpp"
#include "sensor_msgs/msg/laser_scan.hpp"
class LaserScanSubscriber : public rclcpp::Node
{
public:
LaserScanSubscriber() : Node("laser_scan_subscriber")
{
subscription_ = this->create_subscription<sensor_msgs::msg::LaserScan>(
"/scan", 10, std::bind(&LaserScanSubscriber::scan_callback, this, std::placeholders::_1));
}
private:
void scan_callback(const sensor_msgs::msg::LaserScan::SharedPtr scan_msg) const
{
// 获取激光雷达数据
std::vector<float> ranges = scan_msg->ranges;
float range_min = scan_msg->range_min;
float range_max = scan_msg->range_max;
// 遍历所有激光点,计算距离并输出
for (int i = 0; i < ranges.size(); i++)
{
float range = ranges[i];
if (range > range_min && range < range_max)
{
RCLCPP_INFO(this->get_logger(), "Distance at %d degrees: %f meters", i, range);
}
}
}
rclcpp::Subscription<sensor_msgs::msg::LaserScan>::SharedPtr subscription_;
};
int main(int argc, char *argv[])
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<LaserScanSubscriber>());
rclcpp::shutdown();
return 0;
}
```
这个代码创建了一个ROS2节点,订阅名为`/scan`的激光雷达数据,并在每个激光点处计算距离。可以根据需要修改节点名称和订阅主题名称。
阅读全文