要去订阅一个不熟悉的话题的消息该如何做呢?
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之后便可使用