ROS 基础: 在同一个节点里订阅和发布消息

在一些应用中,可能有的人需要在同一个节点中实现订阅一个消息,然后在该消息的回调函数中处理一下这些数据后再发布到另一个topic上。

ROS answers中也有人有相同的疑问,这里贴出Martin Peris答案:

#include <ros/ros.h>class SubscribeAndPublish{public: SubscribeAndPublish() {//Topic you want to publishpub_ = n_.advertise<PUBLISHED_MESSAGE_TYPE>("/published_topic", 1);//Topic you want to subscribesub_ = n_.subscribe("/subscribed_topic", 1, &SubscribeAndPublish::callback, this); } void callback(const SUBSCRIBED_MESSAGE_TYPE& input) {PUBLISHED_MESSAGE_TYPE output;//…. do something with the input and generate the output…pub_.publish(output); }private: ros::NodeHandle n_; ros::Publisher pub_; ros::Subscriber sub_;}//End of class SubscribeAndPublishint main(int argc, char **argv){ //Initiate ROS ros::init(argc, argv, "subscribe_and_publish"); //Create an object of class SubscribeAndPublish that will take care of everything SubscribeAndPublish SAPObject; ros::spin(); return 0;}

(转载请注明作者和出处:未经允许请勿用于商业用途)

,启程了,人的智慧才得以发挥。

ROS 基础: 在同一个节点里订阅和发布消息

相关文章:

你感兴趣的文章:

标签云: