How to publish two different messages at a time.

asked 2020-01-20 23:03:08 -0600

sunkingac4 gravatar image

updated 2020-01-21 00:58:57 -0600

Hi, I need to publish two different sets of PointCloud2 message simultaneously.

int main (int argc, char **argv)
    ros::init (argc, argv, "ros_data_create");
    sensor_msgs::PointCloud2 output1;
    sensor_msgs::PointCloud2 output2;

    ros::Publisher ros_pub1;
    ros::Publisher ros_pub2;

    ros::NodeHandle nh1;
    ros::NodeHandle nh2;
    ros::NodeHandle nh_both;
    int indx = 0;
    ros_pub1 = nh1.advertise<sensor_msgs::PointCloud2> ("ros_output_1", 10);

    pcl::PointCloud<pcl::PointXYZ> cloud;
    cloud.width  = 1000;
    cloud.height = 1;
    cloud.points.resize(cloud.width * cloud.height);

    for (int i = 0; i < cloud.points.size() / 3; i++)
        cloud.points[i].x =; // vector 'vecPointData_1' holds the first set of 'xyz' data stream
        cloud.points[i].y =;
        cloud.points[i].z =;
    pcl::toROSMsg(cloud, output1);


    /* publish second set of xyz data */
    ros_pub2 = nh2.advertise<sensor_msgs::PointCloud2> ("ros_output_2", 10);
    indx = 0;

    pcl::PointCloud<pcl::PointXYZ> cloud2;
    cloud2.width  = 5000;
    cloud2.height = 1;
    cloud2.points.resize(cloud2.width * cloud2.height);

    for (int i = 0; i < cloud2.points.size() / 3; i++)
        cloud2.points[i].x =; // vector 'vecPointData_2' holds the second set of 'xyz' data stream
        cloud2.points[i].y =;
        cloud2.points[i].z =;
    pcl::toROSMsg(cloud2, output2);
    return 0;

Above code publishes the two messages in 'rviz' one after the another.

How to make it to publish simultaneously?

edit retag flag offensive close merge delete



As far as I know, you can't really publish them simultaneously. One option may be to make a custom message that contains data for two different point clouds. Another option may be to assign the same timestamp to the headers of two messages you already have and still publish them separately. I suppose it depends on what you're trying to achieve and why they need to be simultaneous.

tryan gravatar image tryan  ( 2020-01-21 09:35:26 -0600 )edit

I agree with tryan, build a custom msg that holds data for both sub messages.

mhyde64 gravatar image mhyde64  ( 2020-01-21 15:12:04 -0600 )edit

Thanks tyran and mhyde64... I can publish both data by setting the same timestamp to these 2 messages.

sunkingac4 gravatar image sunkingac4  ( 2020-01-23 01:45:52 -0600 )edit