ros 在callback中publish (不用類的方法)


參考鏈接:

https://answers.ros.org/question/214386/how-to-publish-a-message-in-a-callback-function/ 

 

我的意圖是接收到一個自定義的帶時間戳的消息,做簡單操作后,再以原來的時間戳發布出去。

自定義的 msg 叫  RPY

Header header
float32 roll
float32 pitch
float32 yaw

 

talker.cpp

 1 #include <ros/ros.h>
 2 #include <topic_demo/RPY.h>
 3 
 4 int main(int argc, char **argv)
 5 {
 6     ros::init(argc, argv, "rpytalker");
 7     ros::NodeHandle nh;
 8 
 9     topic_demo::RPY msg;
10     msg.roll = 1.0;
11     msg.pitch = 1.0;
12     msg.yaw = 1.0;
13 
14     ros::Publisher pub = nh.advertise<topic_demo::RPY>("rpy_info", 1);
15  
16     ros::Rate loop_rate(2.0);
17 
18     while (ros::ok())
19     {
20         //以指數增長,每隔0.5秒更新一次
21         msg.roll = 1.01 * msg.roll ;
22         msg.pitch = 1.02 * msg.pitch;
23         msg.yaw = 1.03 * msg.yaw;
24 
25         msg.header.stamp = ros::Time::now(); 
26 
27         ROS_INFO("Talker: rpy: r = %f, p = %f, y = %f ",  msg.roll ,msg.pitch, msg.yaw );
28 
29         pub.publish(msg);
30 
31         loop_rate.sleep();
32     }
33 
34     return 0;
35 } 

 

listener.cpp

 1 /*
 2  
 3 這里讀取 rpy ,然后 加個1, 以原有的 時間戳發布出去
 4  
 5 */
 6  
 7 #include <ros/ros.h>
 8 #include <topic_demo/RPY.h>
 9 #include <std_msgs/Float32.h>
10  
11 void rpyCallback(const topic_demo::RPY::ConstPtr &msg , ros::Publisher *pub)
12 { 
13     float roll = msg->roll;
14     float pitch = msg->pitch;
15     float yaw = msg->yaw;
16  
17     std_msgs::Header h = msg->header;
18  
19     ROS_INFO("Listener rpy : r = %f, p = %f, y = %f, time: %d", roll, pitch, yaw, h.stamp );
20  
21     topic_demo::RPY new_msg;
22     new_msg.roll = roll + 1.0;
23     new_msg.pitch = pitch + 1.0;
24     new_msg.yaw = yaw + 1.0;
25  
26     new_msg.header = h;
27  
28     pub->publish(new_msg); // 不能是 pub.publish, 必須是 pub->publish
29  
30     ROS_INFO("Listener plus : r = %f, p = %f, y = %f, time: %d", new_msg.roll, new_msg.pitch, new_msg.yaw, new_msg.header.stamp );
31 }
32  
33 int main(int argc, char **argv)
34 {
35     ros::init(argc, argv, "rpylistener");
36     ros::NodeHandle n;
37      
38     ros::Publisher pub = n.advertise<topic_demo::RPY>("rpy_info_plus", 1);
39  
40     // ros::Subscriber sub = n.subscribe("rpy_info", 1, rpyCallback);
41  
42     ros::Subscriber sub = n.subscribe<topic_demo::RPY>("rpy_info", 0, boost::bind(&rpyCallback, _1, &pub));
43  
44     ros::spin();
45     return 0;
46 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM