一个机器人通常有很多坐标系,tf能够跟踪所有定义的坐标系随时间的变化,以及他们之间的相对位置。
使用view_frames
或rqt_tf_tree
工具查看发布的tf坐标系信息:
# creates a diagram of the frames being broadcast by tf over ROS.
$ rosrun tf view_frames
$ evince frames.pdf
# a runtime tool for visualizing the tree of frames being broadcast over ROS
$ rosrun rqt_tf_tree rqt_tf_tree
查看目标坐标系相对于参考坐标系的变换,它等于从参考到世界坐标系/world的变换乘以从世界坐标系/world到目标的变换的乘积:
$ rosrun tf tf_echo [reference_frame] [target_frame]
#include
#include
#include
std::string turtle_name;
void poseCallback(const turtlesim::PoseConstPtr& msg){
static tf::TransformBroadcaster br;
tf::Transform transform;
// 2D -> 3D
transform.setOrigin( tf::Vector3(msg->x, msg->y, 0.0) );
tf::Quaternion q;
q.setRPY(0, 0, msg->theta);
transform.setRotation(q);
// tf::Transform, 时间戳, parent frame, child frame
br.sendTransform(tf::StampedTransform(transform, ros::Time::now(), "world", turtle_name));
}
int main(int argc, char** argv){
ros::init(argc, argv, "my_tf_broadcaster");
if (argc != 2){ROS_ERROR("need turtle name as argument"); return -1;};
turtle_name = argv[1];
ros::NodeHandle node;
ros::Subscriber sub = node.subscribe(turtle_name+"/pose", 10, &poseCallback);
ros::spin();
return 0;
}
生成一个名字为my_tf_broadcaster
的节点,订阅了turtle_name+"/pose"
消息,在回调函数里发送tf坐标系信息。
在CMakeList.txt
中添加:
add_executable(turtle_tf_broadcaster src/turtle_tf_broadcaster.cpp)
target_link_libraries(turtle_tf_broadcaster ${catkin_LIBRARIES})
#include
#include
#include
#include
int main(int argc, char** argv){
ros::init(argc, argv, "turtle_tf_listener");
ros::NodeHandle node;
// call service "spawn"
ros::service::waitForService("spawn");
ros::ServiceClient add_turtle = node.serviceClient("spawn");
turtlesim::Spawn srv;
add_turtle.call(srv);
// publish topic "turtle2/cmd_vel"
ros::Publisher turtle_vel =
node.advertise("turtle2/cmd_vel", 10);
tf::TransformListener listener;
ros::Rate rate(10.0);
while (node.ok()){
tf::StampedTransform transform;
try{
// 目标坐标系 参考坐标系 最新的tf 用来存放tf的对象
listener.lookupTransform("/turtle2", "/turtle1", ros::Time(0), transform);
}
catch (tf::TransformException ex){
ROS_ERROR("%s",ex.what());
ros::Duration(1.0).sleep();
}
// 转化成turtle2的角度和速度
geometry_msgs::Twist vel_msg;
vel_msg.angular.z = 4.0 * atan2(transform.getOrigin().y(),
transform.getOrigin().x());
vel_msg.linear.x = 0.5 * sqrt(pow(transform.getOrigin().x(), 2) +
pow(transform.getOrigin().y(), 2));
turtle_vel.publish(vel_msg);
rate.sleep();
}
return 0;
}
在CMakeList.txt
中添加:
add_executable(turtle_tf_listener src/turtle_tf_listener.cpp)
target_link_libraries(turtle_tf_listener ${catkin_LIBRARIES})
注意这里的节点,turtle2是在listener节点里画的,所以没有显示出来。只显示了launch文件里的节点和/rosout。
[1] http://wiki.ros.org/tf/Tutorials