0
$\begingroup$

Rosanswers logo

Hi guys, I'm quite new to ROS and I also just start learning C++ in ROS.

I have followed the tutorial ROS/Tutorials/WritingPublisherSubscriber(c++) and already known how to write a publisher and a subscriber separately.

But I wonder can I put a publisher and subscriber in the same node. I searched and found this answer how to put subscriber and publisher in one cpp file ?. Yes, it does put them together, but they just work separately.

What I want to do is Node A published "hello world" to Node B, and Node B can process the messages and then publish the edited resultes to Node C.

I tried a simple node and this is my code based on the sample codes.

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

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

    ros::NodeHandle n;
    ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter2", 1000);
    std_msgs::String msg;
    std::stringstream ss;
    ss << "long time no see";
    msg.data = ss.str();
    chatter_pub.publish(msg);
    ros::spinOnce();
  }
  else
  {
    ROS_INFO("I didn't hear: [%s]", msg->data.c_str());
  }
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "trans");
  ros::NodeHandle n;
  ros::Subscriber sub = n.subscribe("chatter1", 1000, chatterCallback);
  ros::spin();

  return 0;
}

But only the communication between talker and trans works, there is no message on topic chatter2.

Can anyone help me find where is wrong or give me a sample code to study?


Originally posted by shinnqy on ROS Answers with karma: 23 on 2014-05-06

Post score: 0

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

You should create all publishers and subscribers once at node startup. They need to build up a connection to other nodes, which just isn't there yet between two C++ lines.


Originally posted by dornhege with karma: 31395 on 2014-05-06

This answer was ACCEPTED on the original site

Post score: 0

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.