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;
}
The errors are as follows: Errors
Any help in debugging these error would be appreciated. Thanks
For msg you should use:
msg->ranges[360]
And since "pub" is declared in your main function you cannot call it in a different function. You can first declare it globally and initialize it in the main function.
eg:
#include <geometry_msgs/Twist.h>
#include <ros/ros.h>
#include <sensor_msgs/LaserScan.h>
#include <std_msgs/Float32.h>
ros::Publisher pub;
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;
pub = nh.advertise<geometry_msgs::Twist>("/cmd_vel", 1000);
ros::Subscriber sub = nh.subscribe("/kobuki/laser/scan", 1000, laserCallBack);
ros::spin();
return 0;
}
Also, check your package.xml and CMakeLists.txt
Refer to section 3 (Building your Nodes) from http://wiki.ros.org/ROS/Tutorials/WritingPublisherSubscriber%28c%2B%2B%29