ros下如何订阅任意话题

         要去订阅一个不熟悉的话题的消息该如何做呢?

     1、使用rostopic list查看所有话题名称,找到自己想要去订阅的话题名称,这里以/turtle1/pose话题为例

     2、查看话题/turtle1/pose的类型,rostopic type /turtle1/pose,结果如下:

     

       turtlesim/pose


    3、继续运行  rosmsg show  命令查看话题类型turtlesim/pose的详细信息:

       

      rosmsg show /turtle1/pose
      得到结果为:

     

   float32 x
   float32 y
   float32 theta
   float32 linear_velocity
   float32 angular_velocity
    4、这里可以使用 rostopic echo /turtle1/pose 查看话题输出信息

    5、要使用该话题的内容需要包含turtlesim/Pose.h头文件,一般和消息类型挂钩,可以使用下面的api进行查询:

      

    注:ROS各种API查询
    http://docs.ros.org/indigo/api/
    http://docs.ros.org/api/
     所以在文件包含的时候加入语句: 

    #include "turtlesim/Pose.h"
    6、编写回调函数

       

 void chatterCallback_pose(const turtlesim::PoseConstPtr& msg)
   {
      float x, y, theta;
      x=msg->x;
      y=msg->y;
      theta=msg->theta;
      ROS_INFO("I heard pose x:[%f] y:[%f] z:[%f]",x, y, theta);
  }
    许多消息类型格式都是[包名]::[消息文件名][ConstPtr]&     比如:const turtlesim::PoseConstPtr&、

const geometry_msgs::TwistConstPtr&等

    7、主要代码

    

    #include "ros/ros.h"
    #include "std_msgs/String.h"
    #include "turtlesim/Pose.h"

    //#include <sstream>

    void chatterCallback(const std_msgs::String::ConstPtr& msg)
   {
      ROS_INFO("I heard odom:[%s]",msg->data.c_str());
      std::cout<<" chatterCallback run"<<std::endl;
   }

   void chatterCallback_pose(const turtlesim::PoseConstPtr& msg)
   {
      float x, y, theta;
      x=msg->x;
      y=msg->y;
      theta=msg->theta;
      ROS_INFO("I heard pose x:[%f] y:[%f] z:[%f]",x, y, theta);
   }

   int main(int argc, char **argv)
  {
      ros::init(argc, argv, "test1");
      ros::NodeHandle n;

        ros::Subscriber sub = n.subscribe("turtle1/pose",1000,chatterCallback_pose);
      //std::cout<<" for test1"<<std::endl;
      ros::spin();

      return 0;
  }

     8、CMakeLists.txt文件不用再做修改了,还是前面说的在自动生成的文件末尾加两句话用来生成节点test1的可执行文件:

     

    add_executable(test1 src/test1.cpp)
    target_link_libraries(test1 ${catkin_LIBRARIES})
    9、catkin_make之后便可使用


  • 4
    点赞
  • 48
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值