申明:ROS学习参考了古月居老师的Blibli视频,强烈推荐大家看视频学习,本博客仅记录自己的学习经历和心得,欢迎大家一起讨论!
前言:本讲对应古月老师 ROS入门21讲的第17和18讲,综合性比较强。个人认为难度较大,必须好好啃一下,记录自己的学习过程,内容会逐渐补充!
1 机器人坐标变换
博主在大三时期学习过机器人控制系统,其中对此部分知识有很细致的介绍,不过时间过去很久了,需要抽时间好好整理下。在此做一个标记,后续补充相关内容。
2 TF功能包
TF坐标变换:1、广播TF变换 2、监听TF变换
机器人坐标变换
3 小海龟跟随实验
$ sudo apt-get install ros-melodic-turtle-tf
$ roslaunch turtle_tf turtle_tf_demo.launch
$ rosrun turtlesim turtle_teleop_key
$ rosrun tf view_frames
TF位置关系(可以看出turtle1和turtle2都与world坐标系相联系)
其中,红色小龟自由移动,绿色小龟跟随移动,最终位置重合。
rosrun tf tf_echo turtle1 turtle2
使用此命令可以得到当前时刻,turtle1 和turtle2两个坐标系之间的坐标变换,Translation(平移),Rotation(旋转),分别通过四元数、弧度、角度进行描述。
T
t
u
r
t
l
e
1
−
t
u
r
t
l
e
2
=
T
t
u
r
t
l
e
1
−
w
o
r
l
d
∗
T
w
o
r
l
d
−
t
u
r
t
l
e
2
T_{turtle1-turtle2} = T_{turtle1-world}*T_{world-turtle2}
Tturtle1−turtle2=Tturtle1−world∗Tworld−turtle2
在Rviz中表示
4 tf坐标系广播与监听的编程实现
4.1 创建一个功能包
$ cd ~/catkin_ws/src
$ catkin_create_pkg learning_tf roscpp rospy tf turtlesim
4.2 创建tf广播器代码
4.2.1 C++程序
cd ~/catkin_ws/src/learning_tf/src
touch turtle_tf_broadcaster.cpp
/**
* 该例程产生tf数据,订阅turtle1和turtle2的位置信息,广播给tf树
*/
#include <ros/ros.h>
#include <tf/transform_broadcaster.h>
#include <turtlesim/Pose.h>
std::string turtle_name;
void poseCallback(const turtlesim::PoseConstPtr& msg)
{
// 创建tf的广播器
static tf::TransformBroadcaster br;
// 初始化tf数据
tf::Transform transform;
transform.setOrigin( tf::Vector3(msg->x, msg->y, 0.0) );
tf::Quaternion q;
q.setRPY(0, 0, msg->theta);
transform.setRotation(q);
// 广播world与海龟坐标系之间的tf数据
br.sendTransform(tf::StampedTransform(transform, ros::Time::now(), "world", turtle_name));
}
int main(int argc, char** argv)
{
// 初始化ROS节点
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;
};
代码解释:
- 初始化ROS节点
- 输入参数判断是哪一个海龟(使用重映射方法分别命名节点,避免冲突)
- 订阅海龟的Pose话题
- 在回调函数里创建一个TF广播器(TransformBroadcaster)
- 得到海龟的平移矩阵和旋转矩阵,即world与turtle_name的坐标变换关系
- 借助transform将2个节点的坐标变换关系(sendTransform)广播出去,插入到tf树中
4.2.2 Python程序
touch turtle_tf_broadcaster.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#该例程产生tf数据,订阅turtle1和turtle2的位置信息,广播给tf树
import roslib
roslib.load_manifest('learning_tf')
import rospy
import tf
import turtlesim.msg
def handle_turtle_pose(msg, turtlename):
br = tf.TransformBroadcaster()
br.sendTransform((msg.x, msg.y, 0),
tf.transformations.quaternion_from_euler(0, 0, msg.theta),
rospy.Time.now(),
turtlename,
"world")
if __name__ == '__main__':
rospy.init_node('turtle_tf_broadcaster')
turtlename = rospy.get_param('~turtle')
rospy.Subscriber('/%s/pose' % turtlename,
turtlesim.msg.Pose,
handle_turtle_pose,
turtlename)
rospy.spin()
4.3 创建tf监听器代码
4.3.1 C++程序
cd ~/catkin_ws/src/learning_tf/src
touch turtle_tf_listener.cpp
/**
* 该例程监听tf数据,并计算、发布turtle2的速度指令
*/
#include <ros/ros.h>
#include <tf/transform_listener.h>
#include <geometry_msgs/Twist.h>
#include <turtlesim/Spawn.h>
int main(int argc, char** argv)
{
// 初始化ROS节点
ros::init(argc, argv, "my_tf_listener");
// 创建节点句柄
ros::NodeHandle node;
// 请求产生turtle2
ros::service::waitForService("/spawn");
ros::ServiceClient add_turtle = node.serviceClient<turtlesim::Spawn>("/spawn");
turtlesim::Spawn srv;
add_turtle.call(srv);
// 创建发布turtle2速度控制指令的发布者
ros::Publisher turtle_vel = node.advertise<geometry_msgs::Twist>("/turtle2/cmd_vel", 10);
// 创建tf的监听器
tf::TransformListener listener;
ros::Rate rate(10.0);
while (node.ok())
{
// 获取turtle1与turtle2坐标系之间的tf数据
tf::StampedTransform transform;
try
{
listener.waitForTransform("/turtle2", "/turtle1", ros::Time(0), ros::Duration(3.0));
listener.lookupTransform("/turtle2", "/turtle1", ros::Time(0), transform);
}
catch (tf::TransformException &ex)
{
ROS_ERROR("%s",ex.what());
ros::Duration(1.0).sleep();
continue;
}
// 根据turtle1与turtle2坐标系之间的位置关系,发布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;
};
代码解释:
- 初始化ROS节点
- 代码产生一只新的海龟turtle2
- 创建turtle2速度控制指令的发布者
- 创建tf监听器
- 等待变换waitForTransform
- 查询变换lookupTransform,查询turtle1和turtle2之间的之间的位姿变换关系
- 定义turtle2的速度(x方向的线速度和z轴方向的角速度)
- 通过发布者将turtle2速度发布出去
4.3.2 Python程序
touch turtle_tf_broadcaster.cpp
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#该例程监听tf数据,并计算、发布turtle2的速度指令
import roslib
roslib.load_manifest('learning_tf')
import rospy
import math
import tf
import geometry_msgs.msg
import turtlesim.srv
if __name__ == '__main__':
rospy.init_node('turtle_tf_listener')
listener = tf.TransformListener()
rospy.wait_for_service('spawn')
spawner = rospy.ServiceProxy('spawn', turtlesim.srv.Spawn)
spawner(4, 2, 0, 'turtle2')
turtle_vel = rospy.Publisher('turtle2/cmd_vel', geometry_msgs.msg.Twist,queue_size=1)
rate = rospy.Rate(10.0)
while not rospy.is_shutdown():
try:
(trans,rot) = listener.lookupTransform('/turtle2', '/turtle1', rospy.Time(0))
except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException):
continue
angular = 4 * math.atan2(trans[1], trans[0])
linear = 0.5 * math.sqrt(trans[0] ** 2 + trans[1] ** 2)
cmd = geometry_msgs.msg.Twist()
cmd.linear.x = linear
cmd.angular.z = angular
turtle_vel.publish(cmd)
rate.sleep()
4.4 编译设置
在CMakeLists.txt 文件中设置链接库和可执行文件
add_executable(turtle_tf_broadcaster src/turtle_tf_broadcaster.cpp)
target_link_libraries(turtle_tf_broadcaster ${catkin_LIBRARIES})
add_executable(turtle_tf_listener src/turtle_tf_listener.cpp)
target_link_libraries(turtle_tf_listener ${catkin_LIBRARIES})
在工作空间根目录下使用catkin_make指令编译。
4.5 程序运行
4.5.1 C++程序运行
roscore
rosrun turtlesim turtlesim_node
rosrun learning_tf turtle_tf_broadcaster __name:=turtle1_tf_broadcaster /turtle1
rosrun learning_tf turtle_tf_broadcaster __name:=turtle2_tf_broadcaster /turtle2
rosrun learning_tf turtle_tf_listener
rosrun turtlesim turtle_teleop_key
4.5.2 Python程序运行
roscore
rosrun turtlesim turtlesim_node
rosrun learning_tf turtle_tf_broadcaster.py __name:=turtle1_tf_broadcaster _turtle:=turtle1
rosrun learning_tf turtle_tf_broadcaster.py __name:=turtle2_tf_broadcaster _turtle:=turtle2
rosrun learning_tf turtle_tf_listener.py
rosrun turtlesim turtle_teleop_key
本讲结束,学无止境,继续加油!