Doc
Doc

Reputation: 1

How can I add a subscriber in C++ in ROS

So I am trying to add a subscriber to a specific topic. The purpose of the subscriber is to get range messages from the pi_sonar topic and use it in the code. This is the code here: line Follower code

so, if I wanted to add the sonar messages, should it look like this:

void turtlebot::range_sub('pacakge name of sonars'::range msg){
        turtlebot::rng = msg.range;
 }

based on what I was able to understand here I mean…

Is that correct?

I am gonna try it once I have my hands on the robot

Upvotes: 0

Views: 983

Answers (1)

GPrathap
GPrathap

Reputation: 7810

You can follow this tutorial, it explains exactly what you are looking for,

#include <ros/ros.h>
#include <sensor_msgs/Range.h>

void sonarCallback(const sensor_msgs::Range::ConstPtr& msg)
{
  ROS_INFO("Sonar Seq: [%d]", msg->header.seq);
  ROS_INFO("Sonar Range: [%f]", msg->range);
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "infrared_listener");
  ros::NodeHandle n;
  ros::Subscriber sub = n.subscribe("sensor/sonar0", 1000, sonarCallback);
  ros::spin();
  return 0;
}

Basically, you have to create ros::Subscriber whose callback, i.e., sonarCallback, is listening to incoming messages where you can implement your logic what to do with the sonar sensor reading, Please go through the link I shared and if something not clear, update the question accordingly

Upvotes: 0

Related Questions