How to Write Publisher Subscriber for a arrray in ROS C++ ?
I found a code reference for publisher subscriber with array msg in a topic, but then i couldnt find the error im doing in it. Please help me in finding the error.
Publisher Program:
#include <stdio.h>
#include <stdlib.h>
#include "ros/ros.h"
#include "std_msgs/MultiArrayLayout.h"
#include "std_msgs/MultiArrayDimension.h"
#include "std_msgs/Int32MultiArray.h"
int main(int argc, char **argv)
{
ros::init(argc, argv, "arrayPublisher");
ros::NodeHandle n;
ros::Publisher pub = n.advertise<std_msgs::Int32MultiArray>("array", 100);
while (ros::ok())
{
std_msgs::Int32MultiArray array;
//Clear array
array.data.clear();
//for loop, pushing data in the size of the array
for (int i = 0; i < 12; i++)
{
//assign array a random number between 0 and 180.
array.data.push_back(rand() % 180);
}
//Publish array
pub.publish(array);
//Let the world know
ROS_INFO("I published something!");
//Do this.
ros::spinOnce();
//Added a delay so not to spam
sleep(2);
}
}
Subscriber program:
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <iostream>
#include "ros/ros.h"
#include "std_msgs/MultiArrayLayout.h"
#include "std_msgs/MultiArrayDimension.h"
#include "std_msgs/Int32MultiArray.h"
int Arr[90];
void arrayCallback(const std_msgs::Int32MultiArray::ConstPtr& array);
int main(int argc, char **argv)
{
ros::init(argc, argv, "arraySubscriber");
ros::NodeHandle n;
ros::Subscriber sub3 = n.subscribe("array", 100, arrayCallback);
for(int j = 1; j < 12; j++)
{
printf("%d, ", Arr[j]);
}
printf("\n");
ros::spinOnce();
}
void arrayCallback(const std_msgs::Int32MultiArray::ConstPtr& array)
{
int i = 0;
// print all the remaining numbers
for(std::vector<int>::const_iterator it = array->data.begin(); it != array->data.end(); ++it)
{
Arr[i] = *it;
i++;
}
return;
}
While checking the topic , the values are publishing properly. But in the subscriber node something is going wrong i dont know where it is!
Thanks you!
Asked by Rakee003 on 2021-10-09 09:49:11 UTC
Comments
"Something is going wrong" is not a helpful description of the error you are seeing. Please be more specific.
Asked by Mike Scheutzow on 2021-10-10 08:52:48 UTC