Getting Started with ROS for Jetson Nano - Robot Coordinate Transformation


foreword

insert image description here

ROS provides developers with many highly integrated development tools, such as rviz and gazebo. rviz is a three-dimensional visualization tool that can display information such as images, models, paths, etc., but the premise is that these data have been released in the form of topics and parameters. What rviz does is to subscribe to these data and complete the visual rendering. This blogger Mainly rely on rviz's 3D platform to learn coordinate transformation and robot 3D modeling


1. The principle of space coordinate transformation

1. Pose description

Before learning the pose description, we must first understand the nature of the matrix. If we associate the matrix with the function and understand it as a mapping change, then the essence of the matrix is ​​to describe a space transformation of the basis vector, and the determinant expresses exactly the area enclosed by the transformation of the basis vector

insert image description here

i \boldsymbol{i} i andj \boldsymbol{j}j is the simplest pair of basis for forming a two-dimensional plane, and the matrix focuses on the linear transformation of these two pairs of basis vectors, a function similar to a function a ⃗ = f ( b ⃗ )
\vec{a} = f(\vec{b})a =f(b )

比如, [ i j ] \left[ \begin{array}{ccc} i \\ j \end{array} \right ] [ij] This basis passes through[ 3 2 − 2 1 ] \left[ \begin{array}{ccc} 3 & 2\\ -2 & 1 \end{array} \right ][3221] mapping,iii becomes( 3 , − 2 ) (3,-2)(3,2 ) This new basis vector,jjj becomes( 2 , 1 ) (2,1)(2,1 ) With this new basis vector, the entire two-dimensional plane changes as follows:
insert image description here
We put the changed two basis vectors into the matrix as follows, so that this matrix[ 3 2 − 2 1 ] \left[ \begin{ array}{ccc} 3 & 2\\ -2 & 1 \end{array} \right ][3221] represents a transformation mapping to a two-dimensional space, and the two columns are the transformedi \boldsymbol{i}i andj \boldsymbol{j}j

Let's talk about pose, which stands for position and posture. Any rigid body in the space coordinate system OXYZ OXYZIn OX Y Z , position and attitude can be used to accurately and uniquely represent its position status. For the Cartesian coordinate system {A}, any pointppThe position of p can be used as a 3x1 column vectorAP ^{A}PA Parray
AP = [ pxpypz ] ^{A}P = \left[ \begin{array}{ccc} p_{x}\\ p_{y}\\ p_{z} \end{array} \right ]AP= pxpypz

insert image description here
Suppose the main coordinate system is A{A}A,for usXB ˆ , YB ˆ , ZB ˆ \^{X_{B}}, \^{Y_{B}}, \^{Z_{B}}XBˆYBˆZBˆto represent another coordinate system B {B}The unit vectors of the three axes of B , then the coordinate systemB {B}B is relative to the coordinate systemA{A}A boundary cycle with a definedbar = ( AXB ˆ AYB ˆ AZB ˆ ) = [ XB ˆ ∙ XA ˆ YB ˆ ∙ XA ˆ ZB ˆ ∙ XA ˆ XB ˆ ∙ YA ˆ YB ˆ ∙ YA ˆ YB ˆ ∙ OF ˆ XB ˆ ∙ ZA ˆ YB ˆ ∙ ZA ˆ ZB ˆ ∙ ZA ˆ ] _{B}^{A}R = ( ^{A}\^{X_{B}} ^{A}\^{Y_{B}} ^{A}\^{Z_{B}} ) = \left[\begin{array}{ccc}\^{X_{B}} ∙ \^{X_{A}} & \^{Y_{B} } ∙ \^{X_{A}} & \^{Z_{B}} ∙ \^{X_{A}}\\ \^{X_{B}} ∙ \^{Y_{A}} & \^ {Y_{B}} ∙ \^{Y_{A}}& \^{Y_{B}} ∙ \^{Y_{A}}\\ \^{X_{B}} ∙ \^{Z_{A }} & \^{Y_{B}} ∙ \^{Z_{A}} & \^{Z_{B}} ∙ \^{Z_{A}} \end{array} \rightBAR=(AXBˆAYBˆAZBˆ)= XBˆXAˆXBˆYAˆXBˆZAˆYBˆXAˆYBˆYAˆYBˆZAˆZBˆXAˆYBˆYAˆZBˆZAˆ

According to the essence of the matrix we just understood, XA ˆ \^{X_{A}}XAˆAfter being mapped by the matrix, it becomes the unit vector XB ˆ \^{X_{B}}XBˆXA ˆ, YA ˆ, ZA ˆ \^{X_{A}}, \^{Y_{A}}, \^{Z_{A}}XAˆYAˆZAˆThe projection on the three base vectors is exactly XB after synthesis ˆ \^{X_{B}}XBˆYA ˆ \^{Y_{A}}YAˆAfter being mapped by the matrix, it becomes a unit vector YB ˆ \^{Y_{B}}YBˆXA ˆ, YA ˆ, ZA ˆ \^{X_{A}}, \^{Y_{A}}, \^{Z_{A}}XAˆYAˆZAˆThe projection on the three base vectors is exactly YB after synthesis ˆ \^{Y_{B}}YBˆ Z A ˆ \^{Z_{A}} ZAˆAfter being mapped by the matrix, it becomes a unit vector ZB ˆ \^{Z_{B}}ZBˆXA ˆ, YA ˆ, ZA ˆ \^{X_{A}}, \^{Y_{A}}, \^{Z_{A}}XAˆYAˆZAˆThe projection on the three base vectors is exactly ZB after synthesis ˆ \^{Z_{B}}ZBˆ, this rotation matrix is ​​actually the coordinate system A {A}The space transformation of A forms the coordinate systemB {B}B

With B{B}The attitude of the B coordinate system, now we need a position vectorAPBORG ^{A}{P_{BORG}}APBORGto determine B{B}B coordinate system relative toA{A}The relative position of the A coordinate system can finally beB{B}The attitude expression of the B coordinate system is
B = BAR , APBORG {B} = { {_{B}^{A}R, ^{A}{P_{BORG}}}}B=BAR,APBORG

After learning the pose expressions of the two coordinate systems in three-dimensional space, let's discuss the coordinate system A {A}How does a vector in A lie in the coordinate system B{B}Expressed in B , we first discuss the case where the origins of the two coordinate systems coincide, assuming the coordinate system A {A}There is a vectorPP in AP , according to the mapping principle of the matrix, the position vectorPPP is in the coordinate systemA{A}The expression in A is equivalent to the position vector PPP in coordinate systemB{B}The expression in B then from the coordinate system B{B}B maps to the coordinate systemA{A}A
A P = B P B A R ^{A}P = ^{B}P_ {B}^{A}R AP=BPBAR

insert image description here

If the origins of the two coordinate systems do not coincide, we also need to consider the position vector APBORG ^{A}{P_{BORG}} of the origin of the two coordinate systemsAPBORG,from APBORG ^{A}{P_{BORG}}APBORGis in the coordinate system A {A}A is given as a reference, so there is no need for coordinate system mapping, just add vectors directly

AP = BPBAR + APBORG ^{A}P = ^{B}P_{B}^{A}R + ^{A}{P_{BORG}}AP=BPBAR+APBORG
insert image description here

Next we introduce a 4x4homogeneous transformation matrixTo replace the above formula, this expression is more clear and concise
[ AP 1 ] = [ BARAPBORG [ 0 0 0 ] 1 ] [ BP 1 ] \left[ \begin{array}{ccc} ^{A}P\\ 1 \\ \end{array} \right ] = \left[ \begin{array}{ccc} _ {B}^{A}R & ^{A}{P_{BORG}}\\ \left[ \begin{ array}{ccc} 0& 0 & 0\\ \end{array} \right ] & 1\\ \end{array} \right ]\left[ \begin{array}{ccc} ^{B}P \\ 1 \end{array} \right ][AP1]=[BAR[000]APBORG1][BP1]

2. Euler angles and quaternions

Try to imagine an airplane with a coordinate system B{B} at the center of mass of the airplaneB , the coordinate systemB{B}B around itsZZZ- axis rotationα \alphaα angle, and then YYaround itY- axis rotationβ \betaβ angle, and finally XXaround itX- axis rotationγ \gammaγ angle, this set of rotation three angles is called Euler angle. There are three Euler angles, namely yaw (yaw angle), pitch (pitch angle), and roll (roll angle), which represent the angle of rotation around the Z/Y/X axis

insert image description here
According to the process of forming Euler angles above, we can give the mathematical expression of each rotation
RZ ( α ) = [ cos ( α ) − sin ( α ) 0 sin ( α ) cos ( α ) 0 by combining the principle of rotation matrix 0 0 1 ] R_{Z}(\alpha) = \left[ \begin{array}{ccc} cos(\alpha) & -sin(\alpha) & 0\\ sin(\alpha) & cos(\alpha )& 0\\ 0 &0 & 1 \end{array} \right ]RZ( a )= cos ( α )s in ( a )0s in ( a )cos ( α )0001
RY ( β ) = [ cos ( β ) 0 sin ( β ) 0 1 0 − sin ( β ) 0 cos ( β ) ] R_{Y}(\beta) = \left[ \begin{array}{ccc} cos (\beta) & 0 & sin(\beta)\\ 0 & 1& 0\\ -sin(\beta) &0 & cos(\beta) \end{array} \rightRY( b )= cos ( b )0s in ( b )010s in ( b )0cos ( b ).
RX ( γ ) = [ 1 0 0 0 cos ( γ ) − sin ( γ ) 0 sin ( γ ) cos ( γ ) ] R_{X}(\gamma) = \left[ \begin{array}{ccc} & 0 & 0\\ 0 & cos(\gamma)& -sin(\gamma)\\ 0 &sin(\gamma) & cos(\gamma) \end{array} \rightRX( c )= 1000cos ( c )s in ( c )0s in ( c )cos ( c ).
Finally, we integrate the product of the three rotation matrices to get the coordinate system B {B}The new coordinate system B ′ {B^{'}} formed by B after a set of rotationsB , we use a rotation matrixB ′ BR ^{B}_{B^{'}}RBBR to express the coordinate systemB{B}B to coordinate systemB ′ {B^{'}}B' Map relationship
B ′ BRZ − Y − X ( α , β , γ ) = [ cos ( α ) cos ( β ) cos ( α ) sin ( β ) sin ( γ ) − sin ( α ) cos ( γ ) cos ( α ) sin ( β ) cos ( γ ) + sin ( α ) sin ( γ ) sin ( α ) cos ( β ) sin ( α ) sin ( β ) sin ( γ ) + cos ( α ) cos ( γ ) sin ( α ) sin ( β ) cos ( γ ) − cos ( α ) sin ( γ ) − sin ( β ) cos ( β ) sin ( γ ) cos ( β ) cos ( γ ) ] ^{B}_{B^{'}} R_{ZYX} (\alpha,\beta,\gamma )= \left[ \begin{array}{ccc} cos(\alpha)cos(\beta) & cos(\alpha)sin(\beta)sin(\ gamma)-sin(\alpha)cos(\gamma) & cos(\alpha)sin(\beta)cos(\gamma)+sin(\alpha)sin(\gamma)\\ sin(\alpha)cos(\ beta) & sin(\alpha)sin(\beta)sin(\gamma)+cos(\alpha)cos(\gamma)& sin(\alpha)sin(\beta)cos(\gamma)-cos(\alpha )sin(\gamma)\\ -sin(\beta) &cos(\beta)sin(\gamma) & cos(\beta)cos(\gamma) \end{array} \rightBBRZYX( a ,b ,c )= cos ( a ) cos ( b )s in ( a ) cos ( b )s in ( b )cos ( a ) s in ( b ) s in ( c )s in ( a ) cos ( c )s in ( a ) s in ( b ) s in ( c )+cos ( a ) cos ( c )cos ( b ) s in ( c )cos ( a ) s in ( b ) cos ( c )+s in ( a ) s in ( c )s in ( a ) s in ( b ) cos ( c )cos ( a ) s in ( c )cos ( b ) cos ( c )

Quaternions are similar to complex numbers. Quaternions are actually for bases ( a , i ⃗ , j ⃗ , k ⃗ ) {(a,\vec{i},\vec{j},\vec{k})}(a,i ,j ,k ) is a linear combination of a scalar and a 3x1 vector. We use complex numbers as a quaternion analogy. The scalar of the quaternion is the real part of the complex number, and the vector of the quaternion is the imaginary part of the complex number. Multiplication of
insert image description here
quaternions Follow the following properties, multiplication by itself is -1, and the same as other multiplication and cross multiplication properties, follow the right-hand rule
insert image description here

insert image description here
We define q \mathbf{q}q is a unit quaternion, which can be expressed asq = w + xi + yj + zk \mathbf{q} = w +xi +yj+zkq=w+xi+yj+z k , giveq \mathbf{q}q is a unit quaternion
insert image description here

Quaternion q \mathbf{q}The rotation matrix R of q \mathbf{R}_{\mathbf{q}}Rqcan be expressed as
insert image description here

2. Python in ROS implements coordinate transformation

1. Coordinate msg message carrier

The data carrier msg in the subscription publishing model is an important implementation link. The commonly used coordinate data message carrier msg in the realization of coordinate transformation includes geometry_msgs/TransformStamped and geometry_msgs/PointStamped

The following is some data returned by the geometry_msgs/TransformStamped message, and we can get the pose relationship between the two coordinate systems. Generally, we choose the world coordinate system "world" for the parent coordinate system here.

std_msgs/Header header                     #头信息
  uint32 seq                                #|-- 序列号
  time stamp                                #|-- 时间戳
  string frame_id                            #|-- 坐标 ID
string child_frame_id                    #子坐标系的 id
geometry_msgs/Transform transform        #坐标信息
  geometry_msgs/Vector3 translation        #偏移量
    float64 x                                #|-- X 方向的偏移量
    float64 y                                #|-- Y 方向的偏移量
    float64 z                                #|-- Z 方向上的偏移量
  geometry_msgs/Quaternion rotation        #四元数
    float64 x                                
    float64 y                                
    float64 z                                
    float64 w

The following is some data returned by the geometry_msgs/PointStamped message, we can determine the position of the point in the coordinate system to which it belongs

std_msgs/Header header                    #头信息
  uint32 seq                                #|-- 序号
  time stamp                                #|-- 时间戳
  string frame_id                            #|-- 所属坐标系的 id
geometry_msgs/Point point                #点坐标
  float64 x                                    #|-- x y z 坐标
  float64 y
  float64 z

With these message data, we can implement some fun and powerful functions, such as the turtle following in the simulation environment

2. Implementation of the program that the turtle follows

The core of the turtle following implementation is that both turtles A and B will publish coordinate information relative to the world coordinate system, and then subscribe to this information and need to convert and obtain the information of A relative to the coordinate system of B, and finally generate linear velocity and angular velocity information, and control the turtle BSports.

First, in the src directory of the workspace, select the Create Catkin Package option to create a new function package, addtf2、tf2_ros、tf2_geometry_msgs、roscpp rospy std_msgsWait for the dependent package, then create a new scripts folder to store python files, and create a launch folder to store launch files

First, we call the service of ROS to generate the second little turtle. To create the second turtle, we need to use rosservice, and the topic is /spawn

#! /usr/bin/env python

#1.导包
import rospy
from turtlesim.srv import Spawn, SpawnRequest, SpawnResponse

if __name__ == "__main__":
    # 2.初始化 ros 节点
    rospy.init_node("turtle_spawn_p")
    # 3.创建服务客户端
    client = rospy.ServiceProxy("/spawn",Spawn)
    # 4.等待服务启动
    client.wait_for_service()
    # 5.创建请求数据
    req = SpawnRequest()
    req.x = 1.0
    req.y = 1.0
    req.theta = 0
    req.name = "turtle2"
    # 6.发送请求并处理响应
    try:
        response = client.call(req)
        rospy.loginfo("乌龟创建成功,名字是:%s",response.name)
    except Exception as e:
        rospy.loginfo("服务调用失败....")

Then we need to write coordinate message topic publishing node, we pass topic /turtle name/pose/turtle name/pose/ turtle name / pose to obtain the pose of the turtle, and solve it into a coordinate message relative to the world coordinate system, and then publish it

#! /usr/bin/env python

# 1.导包
import rospy
import sys
from turtlesim.msg import Pose
from geometry_msgs.msg import TransformStamped
import tf2_ros
import tf_conversions

turtle_name = ""

def doPose(pose):
    # rospy.loginfo("x = %.2f",pose.x)
    #1.创建坐标系广播器
    broadcaster = tf2_ros.TransformBroadcaster()
    #2.将 pose 信息转换成 TransFormStamped
    tfs = TransformStamped()
    tfs.header.frame_id = "world"
    tfs.header.stamp = rospy.Time.now()

    tfs.child_frame_id = turtle_name
    tfs.transform.translation.x = pose.x
    tfs.transform.translation.y = pose.y
    tfs.transform.translation.z = 0.0

    qtn = tf_conversions.transformations.quaternion_from_euler(0, 0, pose.theta)
    tfs.transform.rotation.x = qtn[0]
    tfs.transform.rotation.y = qtn[1]
    tfs.transform.rotation.z = qtn[2]
    tfs.transform.rotation.w = qtn[3]

    #3.广播器发布 tfs
    broadcaster.sendTransform(tfs)


if __name__ == "__main__":
    # 2.初始化 ros 节点
    rospy.init_node("sub_tfs_p")
    # 3.解析传入的命名空间
    rospy.loginfo("-------------------------------%d",len(sys.argv))
    if len(sys.argv) < 2:
        rospy.loginfo("请传入参数:乌龟的命名空间")
    else:
        turtle_name = sys.argv[1]
    rospy.loginfo("///乌龟:%s",turtle_name)

    rospy.Subscriber(turtle_name + "/pose",Pose,doPose)
    #     4.创建订阅对象
    #     5.回调函数处理订阅的 pose 信息
    #         5-1.创建 TF 广播器
    #         5-2.将 pose 信息转换成 TransFormStamped
    #         5-3.发布
    #     6.spin
    rospy.spin()

Finally, we need to write a coordinate message topic subscription node, by subscribing to the TF coordinate broadcast information of turtle1 and turtle2, find and convert the latest TF coordinate information, convert turtle1 into coordinates relative to turtle2, then calculate the linear velocity and angular velocity and publish it to the turtle movement control topic

#! /usr/bin/env python

# 1.导包
import rospy
import tf2_ros
from geometry_msgs.msg import TransformStamped, Twist
import math

if __name__ == "__main__":
    # 2.初始化 ros 节点
    rospy.init_node("sub_tfs_p")
    # 3.创建 TF 订阅对象
    buffer = tf2_ros.Buffer()
    listener = tf2_ros.TransformListener(buffer)
    # 4.处理订阅到的 TF
    rate = rospy.Rate(10)
    # 创建速度发布对象
    pub = rospy.Publisher("/turtle2/cmd_vel",Twist,queue_size=1000)
    while not rospy.is_shutdown():

        rate.sleep()
        try:
            #def lookup_transform(self, target_frame, source_frame, time, timeout=rospy.Duration(0.0)):
            trans = buffer.lookup_transform("turtle2","turtle1",rospy.Time(0))
            # rospy.loginfo("相对坐标:(%.2f,%.2f,%.2f)",
            #             trans.transform.translation.x,
            #             trans.transform.translation.y,
            #             trans.transform.translation.z
            #             )   
            # 根据转变后的坐标计算出速度和角速度信息
            twist = Twist()
            # 间距 = x^2 + y^2  然后开方
            twist.linear.x = 0.5 * math.sqrt(math.pow(trans.transform.translation.x,2) + math.pow(trans.transform.translation.y,2))
            twist.angular.z = 4 * math.atan2(trans.transform.translation.y, trans.transform.translation.x)

            pub.publish(twist)

        except Exception as e:
            rospy.logwarn("警告:%s",e)

Add executable permissions to python files in the terminal

chmod +777 *.py

Configure the CMakeLists.txt file according to the method in the last note. You will compile three .py files to declare, and then catkin_make:build to see if there is any error after compiling. If there is no error, you can write the launch file.

<launch>
    <node pkg="turtlesim" type="turtlesim_node" name="turtle1" output="screen" />
    <node pkg="turtlesim" type="turtle_teleop_key" name="key_control" output="screen"/>

    <node pkg="xxx" type="xxx.py" name="turtle_spawn" output="screen"/>

    <node pkg="xxx" type="xxx.py" name="tf_pub1" args="turtle1" output="screen"/>
    <node pkg="xxx" type="xxx.py" name="tf_pub2" args="turtle2" output="screen"/>
    <node pkg="xxx" type="xxx.py" name="tf_sub" output="screen"/>
</launch>

After writing the launch file, right-click the launch file to open the terminal and run the launch file to see the effect of the turtle following

roslaunch xxx(功能包) xxx.launch(launch文件)

Summarize

The above are the study notes of robot coordinate transformation. This note briefly introduces the theoretical basis of robot coordinate transformation and the implementation process of TF coordinate transformation in ROS. The importance of robot coordinate transformation is that it can make the robot maintain consistent motion accuracy in different coordinate systems. Because in different coordinate systems, the trajectory and position information of the robot will change. For example, the motion of the robot in the base coordinate system may be linear motion, but the motion in the tool coordinate system may be rotational motion. If the coordinate transformation is not carried out, the robot's trajectory and position information will deviate, causing the robot to be unable to complete the task accurately.

Guess you like

Origin blog.csdn.net/m0_55202222/article/details/130607876