ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
0

Using Publisher inside a Subscriber callback function

asked 2021-08-18 21:34:24 -0500

KhalidOwlWalid gravatar image

updated 2021-08-18 21:41:39 -0500

I want to make make my robot to move towards a wall, but I am having trouble implementing the Subscriber and Publisher in a single cpp file. My implementation is as follows:

#include <geometry_msgs/Twist.h>
#include <ros/ros.h>
#include <sensor_msgs/LaserScan.h>
#include <vector>

class SubscribeAndPublish {
private:
  ros::NodeHandle nh;
  ros::Publisher pub;
  ros::Subscriber sub;

public:
  SubscribeAndPublish();
  void scanCallback(const sensor_msgs::LaserScan::ConstPtr &msg);
};

SubscribeAndPublish::SubscribeAndPublish()
: pub{nh.advertise<geometry_msgs::Twist>("cmd_vel", 10)},
  sub{nh.advertise<sensor_msgs::LaserScan>("kobuki/laser/scan", 10, &SubscribeAndPublish::scanCallback, this)} {}

SubscribeAndPublish::scanCallback(const sensor_msgs::LaserScan::ConstPtr &msg) {

  geometry_msgs::Twist move;
  float frontSensor, rightSensor, leftSensor, distanceToWall;
  double speed, rotationSpeed;

  frontSensor = msg->ranges[359];
  rightSensor = msg->ranges[719];
  leftSensor = msg->ranges[0];
  distanceToWall = 1.0;

  if (frontSensor >= distanceToWall) {
    move.linear.x = speed;
    move.angular.z = 0;
    pub.publish(move);
  }
}

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

  ros::init(argc, argv, "topics_quiz_node");

  SubscribeAndPublish sub_and_pub;

  ros::spin();
  return 0;
}

I tried to follow this solution https://answers.ros.org/question/59725/publishing-to-a-topic-via-subscriber-callback-function/?answer=59738?answer=59738#post-id-59738 but I am receiving this error:

 error: no matching function for call to 'ros::Subscriber::Subscriber(<brace-enclosed initializer list>)'
   19 |       sub{nh.advertise<sensor_msgs::LaserScan>("kobuki/laser/scan", 10, &SubscribeAndPublish::scanCallback, this)} {}

I am still new to roscpp. ^

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-08-19 01:01:48 -0500

mgruhler gravatar image

updated 2021-08-19 01:02:09 -0500

Well, I guess it has to do with trying to advertise using a subscriber :-)

It should be subscribe...

sub{nh.subscribe("kobuki/laser/scan", 10, &SubscribeAndPublish::scanCallback, this)}
edit flag offensive delete link more

Comments

Oh my god, im an idiot.

KhalidOwlWalid gravatar image KhalidOwlWalid  ( 2021-08-19 23:18:01 -0500 )edit
1

happens to all of us :-) Please accept the answer by clicking the checkmark next to it, thanks.

mgruhler gravatar image mgruhler  ( 2021-08-20 06:02:31 -0500 )edit

Question Tools

2 followers

Stats

Asked: 2021-08-18 21:34:24 -0500

Seen: 174 times

Last updated: Aug 19 '21