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

how to put publisher and subscriber in a single Node?

asked 2015-02-04 06:10:51 -0600

Aarif gravatar image

updated 2015-02-04 06:11:43 -0600

hello, i am writing a node which subscribes to /scan topic make some calculations and according to the calculated values it publishes different messages on the /robotState topic in the callback function.

Here is my code:

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

void switcherCallback(const sensor_msgs::LaserScan::ConstPtr& msg)
    ros::NodeHandle p;
    ros::Publisher state_pub = p.advertise<std_msgs::String>("robotState",1000);
    ros::Rate loop_rate(1);
    int f=0;
    for(int i=0; i<msg->ranges.size(); i++){
        std_msgs::String msg;
        std::stringstream ss;
        ss<<"1"; = ss.str();
        std_msgs::String msg;
        std::stringstream ss;
        ss<<"0"; = ss.str();

int main(int argc, char **argv)
    ros::init(argc, argv, "switcher");
    ros::NodeHandle n;
    ros::Subscriber sub = n.subscribe<sensor_msgs::LaserScan>("scan", 1000, switcherCallback);
    return 0;

But whenever i executes the code it shows the following error:

Bus error (core dumped)

i am just wandering why this error is occurred and how can i put both publisher and subscriber in a single node?

edit retag flag offensive close merge delete


hi Aarif ,I am doing the same work,but it do not work .can you tell me how you make it work? thanks a lot

Jie Sky gravatar image Jie Sky  ( 2015-05-06 22:17:29 -0600 )edit

1 Answer

Sort by » oldest newest most voted

answered 2015-02-04 07:13:40 -0600

You shouldn't call ros::spinOnce() inside the callback. What it does is that it checks the subscriber queue, then calls your callback again, so that now you're calling the callback recursively. Instead, process the single message and exit the callback, which will drop you back into the ros::spin() call in main().

Also, you shouldn't re-create the publisher every time you want to publish a message (inside the callback). Instead, create it once (in main) and use it inside the callback. Otherwise, the subscribers won't be able to read the message before the publisher is destroyed again (when exiting the callback).

edit flag offensive delete link more


Thanks @Martin Günther, it worked.

Aarif gravatar image Aarif  ( 2015-02-06 11:52:25 -0600 )edit

hi Aarif ,I am doing the same work,but it do not work .can you tell me how you make it work? thanks a lot

Jie Sky gravatar image Jie Sky  ( 2015-05-06 22:16:57 -0600 )edit

hi @Jie Sky, do exactly as explained in the answer. i hope it will work for you too... :)

Aarif gravatar image Aarif  ( 2015-08-26 04:42:43 -0600 )edit

Question Tools

1 follower


Asked: 2015-02-04 06:10:51 -0600

Seen: 856 times

Last updated: Feb 04 '15