Help please ROS Basic, I still don't understand the syntax

Hello. Can you help me. I’m learning ROS, but I can’t do a basic project, to move a robot facing a wall and turn left when encountering an obstacle. In c++ and ROS 1.
My code doesn’t compile or work:

#include “geometry_msgs/Twist.h”
#include “ros/init.h”
#include “ros/node_handle.h”
#include “ros/publisher.h”
#include <ros/ros.h>
#include <sensor_msgs/LaserScan.h>

void FuncCall(const sensor_msgs::LaserScan::ConstPtr &msg) {
// ROS_INFO(“LaserScan (val,angle)=(%f,%f”, msg->range_min, msg->angle_min);
}

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

ros::init(argc, argv, “topics_quiz_node”);
ros::NodeHandle robot;
ros::Publisher vel_pub =
robot.advertise<geometry_msgs::Twist>(vel_topic, 100);
ros:: laser_sub = robot.subscribe("/kobuki/laser/scan", 10);

while (ros::ok()) {
geometry_msgs::Twist msg;
sensor_msgs::LaserScan lsr;

if (lsr.ranges[0] < 1.0) {
  msg.linear.x = 0;
  msg.angular.x = 0.5;
} else {
  msg.linear.x = 0.5;
  msg.angular.x = 0;
}
msg.linear.y = 0;
msg.linear.z = 0;
msg.angular.y = 0;
msg.angular.z = 0;
tqn_pub.publish(msg);
ros::spin();

}
return 0;
}

Hi @antonio.avezon ,

Welcome to the Community!

The problem seems to be that you are not storing and updating values of the laser scans in your code.
The subscriber has a callback function in which you need to store the laser scan values that can be accessed by the main program.

  1. Include subscriber callback in your robot.subscribe() line.
  2. Make global variables to store laser scan values for front, left and right.
  3. Update the laser scan (global) variable values inside the callback function.
  4. Finally use the laser scan variables in your main code to move the robot based on the laser values.

Also, You have to publish the twist messages within your if/else block. In your code, right before tqn_pub.publish(msg), your msg values right before publishing are 0.0 for both linear and angular. The robot will never move in your case.

My advise to you: Take the C++ for Robotics course (FREE course) to get a grasp on C++ for ROS. Then follow again the tutorial for Publisher and Subscriber with C++ for ROS. Take some time to understand and then code again.
PLEASE DO NOT RUSH LEARNING.

Hope I was helpful.

Regards,
Girish

1 Like