Hello there, I’m working on the course project of ROS2 Basics in 5 days (C++) and I’m running into issues with the real robot. The same exact code is running perfectly in the simulation but the real robot doesn’t seem to be responding. I used the RCLCPP_INFO function to obtain the sensor readings and try to understand how it’s different from the simulation, but I still can’t make sense of it. The Front and Right distances remain unchanged as the robot moves, even when the robot hits the wall. I tried tweaking the code but to no avail. Your help is appreciated. The following is the code I’m using:
#include “rclcpp/rclcpp.hpp”
#include “geometry_msgs/msg/twist.hpp”
#include “sensor_msgs/msg/laser_scan.hpp”
#include
class WallFollowing : public rclcpp::Node
{
public:
WallFollowing() : Node(“move_robot_node”)
{
// Create a publisher for the cmd_vel topic
cmd_vel_publisher_ = this->create_publisher<geometry_msgs::msg::Twist>(“/cmd_vel”, 10);
// Create a subscriber for the laser scan topic
laser_scan_subscription_ = this->create_subscription<sensor_msgs::msg::LaserScan>(
"/scan",
20, [this](const sensor_msgs::msg::LaserScan::SharedPtr msg) {
this->laserCallback(msg);
}
);
}
private:
void laserCallback(const sensor_msgs::msg::LaserScan::SharedPtr laser_msg)
{
// Get the laser readings on the sides of the robot
float right_distance = laser_msg->ranges[laser_msg->ranges.size() * 0.65];
float front_distance = laser_msg->ranges[0];
// Create a Twist message to control the robot's movement
geometry_msgs::msg::Twist twist_msg;
twist_msg.linear.x = 0.1;
twist_msg.angular.z = 0.0;
RCLCPP_INFO(get_logger(), "Right Distance: %f, Front Distance: %f", right_distance, front_distance);
if (right_distance < 0.20)
{
twist_msg.angular.z = -0.1;
twist_msg.linear.x = 0.1;
}
else if (right_distance > 0.30)
{
twist_msg.angular.z = 0.1;
twist_msg.linear.x = 0.1;
}
else if (front_distance < 0.50)
{
twist_msg.linear.x = 0;
twist_msg.angular.z = -0.2;
}
// Publish the twist command
cmd_vel_publisher_->publish(twist_msg);
}
rclcpp::Publisher<geometry_msgs::msg::Twist>::SharedPtr cmd_vel_publisher_;
rclcpp::Subscription<sensor_msgs::msg::LaserScan>::SharedPtr laser_scan_subscription_;
};
int main(int argc, char *argv)
{
rclcpp::init(argc, argv);
auto node = std::make_shared();
rclcpp::spin(node);
rclcpp::shutdown();
return 0;
}