Turtlebot not following commands as instructed

I am trying to solve exercise 4.4 where turtlebot is supposed to avoid a wall
For now I’m trying to make it stop at 1m distance from wall
But it doesnt and continues with same velocity
Laser

#include “ros/node_handle.h”
#include “ros/subscriber.h”
#include “ros/subscription_callback_helper.h”
#include <geometry_msgs/Twist.h>
#include <ros/ros.h>
#include <sensor_msgs/LaserScan.h>

void odom_Cb(const sensor_msgs::LaserScan::ConstPtr &msg) {
ros::NodeHandle nh;
ros::Publisher pub = nh.advertise<geometry_msgs::Twist>(“/cmd_vel”, 1000);
ros::Rate loop_rate(2);

geometry_msgs::Twist vel;

if (msg->ranges[180] >= 2.0) {
vel.linear.x = 0.05;
pub.publish(vel);
// loop_rate.sleep();
ROS_INFO(“gOING AHEAD, %f”, vel.linear.x);
ROS_INFO(“Distance ahead %f”, msg->ranges[360]);

} else {

vel.linear.x = 0;
ROS_INFO("Hitting wall, %f", vel.linear.x);
ROS_INFO("Distance ahead %f", msg->ranges[360]);
pub.publish(vel);
loop_rate.sleep();

}
// vel.linear.x = 0;
// pub.publish(vel);
}

int main(int argc, char **argv) {

ros::init(argc, argv, “topics_quiz_node”);
ros::NodeHandle nh;

ros::Subscriber sub = nh.subscribe(“kobuki/laser/scan”, 1000, odom_Cb);
ros::spin();

return 0;
}

Hi @Elkan163 ,

Welcome to this Community!

I see why your code does not work.
Cause: You have initialized NodeHandle inside your odom_callback function.

You initialize only one node per program in ROS(1).
You can publish/subscribe to other node topics within the same node.

What you should do:

  1. Bring your publisher and rate inside the main() function, underneath the NodeHandle declaration.
  2. Remove the NodeHandle inside your odom_Cb.

That should fix things.

Also, subscriber can use 10 to 100 as message queue. 1000 is too much.

Important: Next post onwards, please use Fenced Code Blocks in Markdown to enclose any of your codes or file contents. This will help us understand your code better - in the proper indentation and format.

Regards,
Girish