# Publisher and subscriber in one ROS node error

Im doing some underwater UUV Gazebo simulation and would like to use the

hector_pose_estimation


package to fuse IMU and Fluid pressure sensors input for pose estimation.

So my Pressure Sensor has sensor_msgs/FluidPressure but the package wants pressure_height (geometry_msgs/PointStamped) as input. So I created a ROS C++ node to republish sensor_msgs/FluidPressure as the geometry_msgs/PointStamped. The code compiled with no error, but when run it I got error. Firstly, this is the code

#include "ros/ros.h"
#include "sensor_msgs/FluidPressure.h"
#include <std_msgs/Float64.h>
#include <geometry_msgs/PointStamped.h>

double current_pressure;
double depth;
ros::Publisher pub_ ;
geometry_msgs::PointStamped output;

void pressureCallback(const sensor_msgs::FluidPressure::ConstPtr& msg)
{

current_pressure= msg->fluid_pressure;

depth=current_pressure / (997.04*9.8);

//geometry_msgs::PointStamped::ConstPtr& output;

output.point.z = depth;
//positions_pub.publish(output_msg);

//output.z=depth;
pub_.publish(output);

}

int main(int argc, char **argv)
{
ros::init(argc, argv, "pressure_republisher");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("/rexrov2/pressure", 10, pressureCallback);
ros::spin();
return 0;
}


And when run it this it the ERROR:

[FATAL] [1633258406.824329181, 173.610000000]: ASSERTION FAILED
file = /opt/ros/melodic/include/ros/publisher.h
line = 106
cond = false
message =
[FATAL] [1633258406.826511155, 173.612000000]: Call to publish() on an invalid Publisher
[FATAL] [1633258406.826551511, 173.612000000]:


Any help?

Try swapping the order in your main function, so your publisher exists before you start the subscriber callback. I also haven't tried running a publisher and subscriber from the same node handle and can't seem to find anything that explicitly says you can or can't do that.

If just swapping the order doesn't work, then try making separate node handles, one for the publisher and one for the subscriber.

• ok. fix it. ros::Subscriber sub = n.subscribe("/rexrov2/pressure", 10, pressureCallback); pub = n.advertise<geometry_msgs::PointStamped>("pressure_height", 1);` This works
– bob
Oct 3 at 14:45

I believe you need to remove the declaration of the global ROS publisher outside the main function.

• yes done it. Thanks. It works now
– bob
Oct 3 at 15:45