在同一节点中同时拥有订阅者和发布者的问题

Issues with having both subscriber and publisher in the same node

目前,我有一个节点必须同时具有订阅者和发布者。但是,我在构建catkin时遇到了某些错误。

#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;
}

报错如下: Errors

如能帮助调试这些错误,我们将不胜感激。谢谢

对于消息你应该使用:

msg->ranges[360]

并且由于“pub”是在您的主函数中声明的,因此您不能在其他函数中调用它。可以先全局声明,在main函数中初始化。

例如:

#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;
}

此外,请检查您的 package.xml 和 CMakeLists.txt

请参阅 http://wiki.ros.org/ROS/Tutorials/WritingPublisherSubscriber%28c%2B%2B%29

中的第 3 部分(构建您的节点)