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

how to put subscriber and publisher in one cpp file ?

asked 2011-12-11 04:50:01 -0600

maruchi gravatar image

Hi, I have a limited knowledge in C++ so that feel a difficulty in combining a subscriber and a publisher in one C++ file. Based on the tutorial, http://www.ros.org/wiki/ROS/Tutorials/WritingPublisherSubscriber%28c%2B%2B%29 , could anybody give some directions on making one C++ file which includes a subscriber and a publisher ?

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
11

answered 2011-12-11 10:57:00 -0600

karthik gravatar image

Hi, Like there is 1 subscriber and 1 publisher in the tutorial. Try to write 2 chatters. i.e each chatter should be able to listen and also talk. In the subscriber of the tutorial add a publisher with different topic. Here is example code. I haven't executed it but it should be simple enough to understand.

#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>

void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
  ROS_INFO("I heard: [%s]", msg->data.c_str());
}

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

  ros::init(argc, argv, "listener");   
  ros::NodeHandle n;   
  ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);
  ros::Publisher chatter_pub = n.advertise<std_msgs::String>("different_chatter", 1000);

  ros::Rate loop_rate(10);   

  int count = 0;
  while (ros::ok())
  {

    std_msgs::String msg;

    std::stringstream ss;
    ss << "hello world " << count;
    msg.data = ss.str();

    ROS_INFO("%s", msg.data.c_str());


    chatter_pub.publish(msg);

    ros::spinOnce();

    loop_rate.sleep();
    ++count;
  }


  ros::spin();

  return 0;
}

Now you can write the second chatter listening to "different_chatter" and publishing to "chatter" topics. Hope this helps,

Karthik

edit flag offensive delete link more

Comments

Karthik, thanks for your help. If it is possible, could you put some comment to my question on here, http://answers.ros.org/question/3274/how-to-add-a-subscriber-in-keyboard-teleop
maruchi gravatar image maruchi  ( 2011-12-11 14:23:37 -0600 )edit
1

answered 2016-01-21 06:03:58 -0600

sxin gravatar image
edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2011-12-11 04:50:01 -0600

Seen: 10,622 times

Last updated: Dec 11 '11