Issues with having both subscriber and publisher in the same node
Currently, I have a node that has to have both the subscriber and publisher. However, I am having certain errors when I catkin build.
#include <geometry_msgs/Twist.h>
#include <ros/ros.h>
#include <sensor_msgs/LaserScan.h>
#include <std_msgs/Float32.h>
void laserCallBack(const sensor_msgs::LaserScan::ConstPtr &msg) {
geometry_msgs::Twist reply;
if (msg.ranges[360] >= 1.0) {
reply.linear.x = 0.5;
reply.angular.z = 0.0;
pub.publish(reply);
} else if (msg.ranges[360] < 1.0) {
reply.linear.x = 0.0;
reply.angular.z = 0.5;
pub.publish(reply);
}
}
int main(int argc, char **argv) {
ros::init(argc, argv, "topics_quiz_node");
ros::NodeHandle nh;
ros::Publisher pub = nh.advertise<geometry_msgs::Twist>("/cmd_vel", 1000);
ros::Subscriber sub = nh.subscribe("/kobuki/laser/scan", 1000, laserCallBack);
ros::spin();
return 0;
}
I am trying to have both the subscriber and publisher in a node. The node will subscribe to laser scan and publish back to the cmd_vel.
The errors are as follows:
/home/user/catkin_ws/src/topics_quiz/src/topics_quiz_node.cpp: In function 'void laserCallBack(const ConstPtr&)': /home/user/catkin_ws/src/topics_quiz/src/topics_quiz_node.cpp:9:11: error: 'const ConstPtr' {aka 'const class boost::shared_ptr<const sensor_msgs::laserscan_<std::allocator<void=""> > >'} has no member named 'ranges' 9 | if (msg.ranges[360] >= 1.0) { | ^~~~~~
/home/user/catkin_ws/src/topics_quiz/src/topics_quiz_node.cpp:12:5: error: 'pub' was not declared in this scope 12 | pub.publish(reply); | ^~~
/home/user/catkin_ws/src/topics_quiz/src/topics_quiz_node.cpp:13:18: error: 'const ConstPtr' {aka 'const class boost::shared_ptr<const sensor_msgs::laserscan_<std::allocator<void=""> > >'} has no member named 'ranges' 13 | } else if (msg.ranges[360] < 1.0) { | ^~~~~~
/home/user/catkin_ws/src/topics_quiz/src/topics_quiz_node.cpp:16:5: error: 'pub' was not declared in this scope 16 | pub.publish(reply); | ^~~ make[2]: * [CMakeFiles/topics_quiz_node.dir/build.make:63: CMakeFiles/topics_quiz_node.dir/src/topics_quiz_node.cpp.o]
Error 1 make[1]: * [CMakeFiles/Makefile2:250: CMakeFiles/topics_quiz_node.dir/all] Error 2 make: * [Makefile:141: all] Error 2 cd /home/user/catkin_ws/build/topics_quiz; catkin build --get-env topics_quiz | catkin env -si /usr/bin/make --jobserver-auth=3,4; cd -