This is a simple LiDAR code example. For this activity, we will not make any changes to Constants.h; we will only work with Robot.h and Robot.cpp. In this code, the LiDAR is connected through the USB port and is used to collect distance data while the robot is running. The code starts the LiDAR when the robot is enabled and stops it when the robot is disabled. It then reads the scan data and sends the distance values to SmartDashboard so that you can monitor what the sensor is seeing.
Robot.h
#pragma once
#include <frc/TimedRobot.h>
#include "studica/Lidar.h"
class Robot : public frc::TimedRobot {
public:
void RobotInit() override;
void RobotPeriodic() override;
void DisabledInit() override;
void DisabledPeriodic() override;
void AutonomousInit() override;
void AutonomousPeriodic() override;
void TeleopInit() override;
void TeleopPeriodic() override;
void TestPeriodic() override;
private:
studica::Lidar m_Lidar{studica::Lidar::Port::kUSB1};
studica::Lidar::ScanData scandata = {{0.0}, {0.0}};
};
Robot.cpp
#include "Robot.h"
#include <frc/smartdashboard/SmartDashboard.h>
void Robot::RobotInit(){}
void Robot::RobotPeriodic()
{
scandata = m_Lidar.GetData();
frc::SmartDashboard::PutNumber("Lidar Front", scandata.distance[90]);
}
void Robot::DisabledInit()
{
m_Lidar.Stop();
}
void Robot::DisabledPeriodic() {}
void Robot::AutonomousInit()
{
m_Lidar.Start();
}
void Robot::AutonomousPeriodic() {}
void Robot::TeleopInit()
{
m_Lidar.Start();
}
void Robot::TeleopPeriodic() {}
void Robot::TestPeriodic() {}
#ifndef RUNNING_FRC_TESTS
int main() { return frc::StartRobot<Robot>(); }
#endif
Use this LiDAR code to make the robot react to an object in front of it. For example, make the robot move forward until the LiDAR detects an object at a certain distance, then stop automatically.