Using Publisher inside a Subscriber callback function
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. ^