intmain(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 < 90; i++) { //assign array a random number between 0 and 255. array.data.push_back(rand() % 255); } //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); }
voidarrayCallback(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++; }
#This message holds a collection of 3d points, plus optional additional information about each point. #Each Point32 should be interpreted as a 3d point in the frame given in the header
Header header geometry_msgs/Point32[] points #Array of 3d points ChannelFloat32[] channels #Each channel should have the same number of elements as points array, and the data in each channel should correspond 1:1 with each point
wiki 上介绍,在ROS中,想在回调函数中发布消息,有两个思路: 1、把函数写成类的形式,把需要的一些变量在类中声明为全局变量。【推荐,模块化好】 2、在函数中,把回调函数需要调用的变量声明为全局变量。也可以解决这个问题。【不好,不符合面向对象的风格】 下面的例子是在同一个节点中实现订阅一个消息,然后在该消息的回调函数中处理一下这些数据后再发布到另一个topic上。
classSubscribeAndPublish { public: SubscribeAndPublish() { //Topic you want to publish pub_ = n_.advertise<PUBLISHED_MESSAGE_TYPE>("/published_topic", 1); //PUBLISHED_MESSAGE_TYPE例如std_msgs::String
//Topic you want to subscribe sub_ = n_.subscribe("/subscribed_topic", 1, &SubscribeAndPublish::callback, this); //注意这里,和wiki上不一样。&SubscribeAndPublish这个是类名 //之所以用this,是因为第四个参数是一个指向【回调函数所在对象】的指针,官方文档例子里把sub定义在了类外面,我们把sub定义在了类的构造函数里面,所以this就是在实例化对象的时候指向对象的指针。(关于this:当调用成员函数a.volume 时,编译系统就把对象a的起始地址赋给this指针;构造函数:建立对象时自动执行。结合两者,在本例中建立类对象时,自动生成指向本对象的指针。) }
//SUBSCRIBED_MESSAGE_TYPE例如std_msgs::String,记得&要保留 voidcallback(const SUBSCRIBED_MESSAGE_TYPE& input) { PUBLISHED_MESSAGE_TYPE output; //.... do something with the input and generate the output... //output = ... pub_.publish(output); }