机器人系统ros2-开发学习实践15-模拟用 URDF 建模 步行机器人行走示例

67 篇文章 1 订阅
56 篇文章 48 订阅

目标:

本教程将向您展示如何建模行走机器人、将状态发布为tf2消息并在 Rviz 中查看模拟。首先,我们创建描述机器人组件的 URDF 模型。接下来,我们编写一个节点来模拟运动并发布 JointState 和变换。然后我们使用robot_state_publisher将整个机器人状态发布到/tf2。

在这里插入图片描述

步骤流程:

  1. 创建包

创建目录:

mkdir -p second_ros2_ws/src

然后创建包:

cd second_ros2_ws/src
ros2 pkg create --build-type ament_python --license Apache-2.0 urdf_tutorial_r2d2 --dependencies rclpy
cd urdf_tutorial_r2d2

您现在应该会看到一个urdf_tutorial_r2d2文件夹。接下来,您将对其进行一些更改

2 创建 URDF 文件

mkdir -p urdf
在这里插入图片描述

写入urdf. 用vscode 打开目录,在 新建r2d2.urdf ,代码如下:
在这里插入图片描述

<robot name="r2d2">

  <link name="axis">
    <visual>
      <origin xyz="0 0 0" rpy="1.57 0 0" />
      <geometry>
        <cylinder radius="0.01" length=".5" />
      </geometry>
      <material name="gray">
        <color rgba=".2 .2 .2 1" />
      </material>
    </visual>

    <collision>
      <origin xyz="0 0 0" rpy="1.57 0 0" />
      <geometry>
        <cylinder radius="0.01" length=".5" />
      </geometry>
      <contact_coefficients mu="0" kp="1000.0" kd="1.0"/>
    </collision>
  </link>

  <link name="leg1">
    <inertial>
      <mass value="1"/>
      <inertia ixx="1e-3" ixy="0" ixz="0" iyy="1e-3" iyz="0" izz="1e-3" />
      <origin/>
    </inertial>

    <visual>
      <origin xyz="0 0 -.3" />
      <geometry>
        <box size=".20 .10 .8" />
      </geometry>
      <material name="white">
        <color rgba="1 1 1 1"/>
      </material>
    </visual>

    <collision>
      <origin xyz="0 0 -.3" />
      <geometry>
        <box size=".20 .10 .8" />
      </geometry>
      <contact_coefficients mu="0" kp="1000.0" kd="1.0"/>
    </collision>
  </link>

  <joint name="leg1connect" type="fixed">
    <origin xyz="0 .30 0" />
    <parent link="axis"/>
    <child link="leg1"/>
  </joint>

  <link name="leg2">
    <inertial>
      <mass value="1"/>
      <inertia ixx="1e-3" ixy="0" ixz="0" iyy="1e-3" iyz="0" izz="1e-3" />
      <origin/>
    </inertial>

    <visual>
      <origin xyz="0 0 -.3" />
      <geometry>
        <box size=".20 .10 .8" />
      </geometry>
      <material name="white">
        <color rgba="1 1 1 1"/>
      </material>
    </visual>

    <collision>
      <origin xyz="0 0 -.3" />
      <geometry>
        <box size=".20 .10 .8" />
      </geometry>
      <contact_coefficients mu="0" kp="1000.0" kd="1.0"/>
    </collision>
  </link>

  <joint name="leg2connect" type="fixed">
    <origin xyz="0 -.30 0" />
    <parent link="axis"/>
    <child link="leg2"/>
  </joint>

  <link name="body">
    <inertial>
      <mass value="1"/>
      <inertia ixx="1e-3" ixy="0" ixz="0" iyy="1e-3" iyz="0" izz="1e-3" />
      <origin/>
    </inertial>

    <visual>
      <origin xyz="0 0 -0.2" />
      <geometry>
        <cylinder radius=".20" length=".6"/>
      </geometry>
      <material name="white"/>
    </visual>

    <collision>
      <origin xyz="0 0 0.2" />
      <geometry>
        <cylinder radius=".20" length=".6"/>
      </geometry>
      <contact_coefficients mu="0" kp="1000.0" kd="1.0"/>
    </collision>
  </link>

  <joint name="tilt" type="revolute">
    <parent link="axis"/>
    <child link="body"/>
    <origin xyz="0 0 0" rpy="0 0 0" />
    <axis xyz="0 1 0" />
    <limit upper="0" lower="-.5" effort="10" velocity="10" />
  </joint>

  <link name="head">
    <inertial>
      <mass value="1"/>
      <inertia ixx="1e-3" ixy="0" ixz="0" iyy="1e-3" iyz="0" izz="1e-3" />
      <origin/>
    </inertial>

    <visual>
      <geometry>
        <sphere radius=".4" />
      </geometry>
      <material name="white" />
    </visual>

    <collision>
      <origin/>
      <geometry>
        <sphere radius=".4" />
      </geometry>
      <contact_coefficients mu="0" kp="1000.0" kd="1.0"/>
    </collision>
  </link>

  <joint name="swivel" type="continuous">
    <origin xyz="0 0 0.1" />
    <axis xyz="0 0 1" />
    <parent link="body"/>
    <child link="head"/>
  </joint>

  <link name="rod">
    <inertial>
      <mass value="1"/>
      <inertia ixx="1e-3" ixy="0" ixz="0" iyy="1e-3" iyz="0" izz="1e-3" />
      <origin/>
    </inertial>

    <visual>
      <origin xyz="0 0 -.1" />
      <geometry>
        <cylinder radius=".02" length=".2" />
      </geometry>
      <material name="gray" />

    </visual>

    <collision>
      <origin/>
      <geometry>
        <cylinder radius=".02" length=".2" />
      </geometry>
      <contact_coefficients mu="0" kp="1000.0" kd="1.0"/>
    </collision>
  </link>

  <joint name="periscope" type="prismatic">
    <origin xyz=".12 0 .15" />
    <axis xyz="0 0 1" />
    <limit upper="0" lower="-.5" effort="10" velocity="10" />
    <parent link="head"/>
    <child link="rod"/>
  </joint>

  <link name="box">
    <inertial>
      <mass value="1"/>
      <inertia ixx="1e-3" ixy="0" ixz="0" iyy="1e-3" iyz="0" izz="1e-3" />
      <origin/>
    </inertial>

    <visual>
      <geometry>
        <box size=".05 .05 .05" />
      </geometry>
      <material name="blue" >
        <color rgba="0 0 1 1" />
      </material>
    </visual>

    <collision>
      <origin/>
      <geometry>
        <box size=".05 .05 .05" />
      </geometry>
      <contact_coefficients mu="0" kp="1000.0" kd="1.0"/>
    </collision>
  </link>

  <joint name="boxconnect" type="fixed">
    <origin xyz="0 0 0" />
    <parent link="rod"/>
    <child link="box"/>
  </joint>

</robot>

上述urdf 说明:

r2d2 机器人模型
│
├── Link: axis
│   ├── Visual: Cylinder (radius: 0.01, length: 0.5, color: gray)
│   └── Collision: Cylinder (radius: 0.01, length: 0.5)
│
├── Link: leg1
│   ├── Inertial: mass=1, inertia=(1e-3, 1e-3, 1e-3)
│   ├── Visual: Box (size: 0.20, 0.10, 0.8, color: white)
│   └── Collision: Box (size: 0.20, 0.10, 0.8)
│
├── Joint: leg1connect (type: fixed)
│   ├── Parent: axis
│   └── Child: leg1
│
├── Link: leg2
│   ├── Inertial: mass=1, inertia=(1e-3, 1e-3, 1e-3)
│   ├── Visual: Box (size: 0.20, 0.10, 0.8, color: white)
│   └── Collision: Box (size: 0.20, 0.10, 0.8)
│
├── Joint: leg2connect (type: fixed)
│   ├── Parent: axis
│   └── Child: leg2
│
├── Link: body
│   ├── Inertial: mass=1, inertia=(1e-3, 1e-3, 1e-3)
│   ├── Visual: Cylinder (radius: 0.20, length: 0.6, color: white)
│   └── Collision: Cylinder (radius: 0.20, length: 0.6)
│
├── Joint: tilt (type: revolute)
│   ├── Parent: axis
│   └── Child: body
│
├── Link: head
│   ├── Inertial: mass=1, inertia=(1e-3, 1e-3, 1e-3)
│   ├── Visual: Sphere (radius: 0.4, color: white)
│   └── Collision: Sphere (radius: 0.4)
│
├── Joint: swivel (type: continuous)
│   ├── Parent: body
│   └── Child: head
│
├── Link: rod
│   ├── Inertial: mass=1, inertia=(1e-3, 1e-3, 1e-3)
│   ├── Visual: Cylinder (radius: 0.02, length: 0.2, color: gray)
│   └── Collision: Cylinder (radius: 0.02, length: 0.2)
│
├── Joint: periscope (type: prismatic)
│   ├── Parent: head
│   └── Child: rod
│
├── Link: box
│   ├── Inertial: mass=1, inertia=(1e-3, 1e-3, 1e-3)
│   ├── Visual: Box (size: 0.05, 0.05, 0.05, color: blue)
│   └── Collision: Box (size: 0.05, 0.05, 0.05)
│
└── Joint: boxconnect (type: fixed)
    ├── Parent: rod
    └── Child: box

详细描述

  • Link: axis

Visual: 描述一个灰色的圆柱体,半径为0.01,长度为0.5。
Collision: 与Visual部分相同的圆柱体,用于碰撞检测。

  • Link: leg1

  • Inertial: 设置了质量为1的惯性属性。
    Visual: 描述一个白色的长方体,尺寸为0.20x0.10x0.8。
    Collision: 与Visual部分相同的长方体,用于碰撞检测。

  • Joint: leg1connect

Type: 固定关节。
Parent: axis。
Child: leg1。
Link: leg2

Inertial: 设置了质量为1的惯性属性。
Visual: 描述一个白色的长方体,尺寸为0.20x0.10x0.8。
Collision: 与Visual部分相同的长方体,用于碰撞检测。
Joint: leg2connect

Type: 固定关节。
Parent: axis。
Child: leg2。
Link: body

Inertial: 设置了质量为1的惯性属性。
Visual: 描述一个白色的圆柱体,半径为0.20,长度为0.6。
Collision: 与Visual部分相同的圆柱体,用于碰撞检测。
Joint: tilt

Type: 转动关节。
Parent: axis。
Child: body。
Link: head

Inertial: 设置了质量为1的惯性属性。
Visual: 描述一个白色的球体,半径为0.4。
Collision: 与Visual部分相同的球体,用于碰撞检测。
Joint: swivel

Type: 连续旋转关节。
Parent: body。
Child: head。
Link: rod

Inertial: 设置了质量为1的惯性属性。
Visual: 描述一个灰色的圆柱体,半径为0.02,长度为0.2。
Collision: 与Visual部分相同的圆柱体,用于碰撞检测。

  • Joint: periscope

  • Type: 伸缩关节。
    Parent: head。
    Child: rod。
    Link: box

  • Inertial: 设置了质量为1的惯性属性。
    Visual: 描述一个蓝色的长方体,尺寸为0.05x0.05x0.05。
    Collision: 与Visual部分相同的长方体,用于碰撞检测。
    Joint: boxconnect

Type: 固定关节。
Parent: rod。
Child: box。


配置rviz

在urdf 目录中继续 新增rviz 配置文件 r2d2.rviz , 文件内容如下:

Panels:
  - Class: rviz_common/Displays
    Help Height: 78
    Name: Displays
    Property Tree Widget:
      Expanded:
        - /Global Options1
        - /Status1
        - /TF1
        - /RobotModel1
        - /RobotModel1/Description Topic1
      Splitter Ratio: 0.5
    Tree Height: 617
  - Class: rviz_common/Selection
    Name: Selection
  - Class: rviz_common/Tool Properties
    Expanded:
      - /2D Goal Pose1
      - /Publish Point1
    Name: Tool Properties
    Splitter Ratio: 0.5886790156364441
  - Class: rviz_common/Views
    Expanded:
      - /Current View1
    Name: Views
    Splitter Ratio: 0.5
Visualization Manager:
  Class: ""
  Displays:
    - Alpha: 0.5
      Cell Size: 1
      Class: rviz_default_plugins/Grid
      Color: 160; 160; 164
      Enabled: true
      Line Style:
        Line Width: 0.029999999329447746
        Value: Lines
      Name: Grid
      Normal Cell Count: 0
      Offset:
        X: 0
        Y: 0
        Z: 0
      Plane: XY
      Plane Cell Count: 10
      Reference Frame: <Fixed Frame>
      Value: true
    - Class: rviz_default_plugins/TF
      Enabled: true
      Frame Timeout: 15
      Frames:
        All Enabled: true
        axis:
          Value: true
        body:
          Value: true
        box:
          Value: true
        head:
          Value: true
        leg1:
          Value: true
        leg2:
          Value: true
        odom:
          Value: true
        rod:
          Value: true
      Marker Scale: 1
      Name: TF
      Show Arrows: true
      Show Axes: true
      Show Names: false
      Tree:
        odom:
          axis:
            body:
              head:
                rod:
                  box:
                    {}
            leg1:
              {}
            leg2:
              {}
      Update Interval: 0
      Value: true
    - Alpha: 1
      Class: rviz_default_plugins/RobotModel
      Collision Enabled: false
      Description File: ""
      Description Source: Topic
      Description Topic:
        Depth: 5
        Durability Policy: Volatile
        History Policy: Keep Last
        Reliability Policy: Reliable
        Value: /robot_description
      Enabled: true
      Links:
        All Links Enabled: true
        Expand Joint Details: false
        Expand Link Details: false
        Expand Tree: false
        Link Tree Style: Links in Alphabetic Order
        axis:
          Alpha: 1
          Show Axes: false
          Show Trail: false
          Value: true
        body:
          Alpha: 1
          Show Axes: false
          Show Trail: false
          Value: true
        box:
          Alpha: 1
          Show Axes: false
          Show Trail: false
          Value: true
        head:
          Alpha: 1
          Show Axes: false
          Show Trail: false
          Value: true
        leg1:
          Alpha: 1
          Show Axes: false
          Show Trail: false
          Value: true
        leg2:
          Alpha: 1
          Show Axes: false
          Show Trail: false
          Value: true
        rod:
          Alpha: 1
          Show Axes: false
          Show Trail: false
          Value: true
      Name: RobotModel
      TF Prefix: ""
      Update Interval: 0
      Value: true
      Visual Enabled: true
  Enabled: true
  Global Options:
    Background Color: 48; 48; 48
    Fixed Frame: odom
    Frame Rate: 30
  Name: root
  Tools:
    - Class: rviz_default_plugins/Interact
      Hide Inactive Objects: true
    - Class: rviz_default_plugins/MoveCamera
    - Class: rviz_default_plugins/Select
    - Class: rviz_default_plugins/FocusCamera
    - Class: rviz_default_plugins/Measure
      Line color: 128; 128; 0
    - Class: rviz_default_plugins/SetInitialPose
      Topic:
        Depth: 5
        Durability Policy: Volatile
        History Policy: Keep Last
        Reliability Policy: Reliable
        Value: /initialpose
    - Class: rviz_default_plugins/SetGoal
      Topic:
        Depth: 5
        Durability Policy: Volatile
        History Policy: Keep Last
        Reliability Policy: Reliable
        Value: /goal_pose
    - Class: rviz_default_plugins/PublishPoint
      Single click: true
      Topic:
        Depth: 5
        Durability Policy: Volatile
        History Policy: Keep Last
        Reliability Policy: Reliable
        Value: /clicked_point
  Transformation:
    Current:
      Class: rviz_default_plugins/TF
  Value: true
  Views:
    Current:
      Class: rviz_default_plugins/Orbit
      Distance: 10
      Enable Stereo Rendering:
        Stereo Eye Separation: 0.05999999865889549
        Stereo Focal Distance: 1
        Swap Stereo Eyes: false
        Value: false
      Focal Point:
        X: 0
        Y: 0
        Z: 0
      Focal Shape Fixed Size: true
      Focal Shape Size: 0.05000000074505806
      Invert Z Axis: false
      Name: Current View
      Near Clip Distance: 0.009999999776482582
      Pitch: 0.459797203540802
      Target Frame: <Fixed Frame>
      Value: Orbit (rviz)
      Yaw: 4.618575572967529
    Saved: ~
Window Geometry:
  Displays:
    collapsed: false
  Height: 846
  Hide Left Dock: false
  Hide Right Dock: false
  QMainWindow State: 000000ff00000000fd000000040000000000000156000002f4fc0200000008fb0000001200530065006c0065006300740069006f006e00000001e10000009b0000005c00fffffffb0000001e0054006f006f006c002000500072006f007000650072007400690065007302000001ed000001df00000185000000a3fb000000120056006900650077007300200054006f006f02000001df000002110000018500000122fb000000200054006f006f006c002000500072006f0070006500720074006900650073003203000002880000011d000002210000017afb000000100044006900730070006c006100790073010000003d000002f4000000c900fffffffb0000002000730065006c0065006300740069006f006e00200062007500660066006500720200000138000000aa0000023a00000294fb00000014005700690064006500530074006500720065006f02000000e6000000d2000003ee0000030bfb0000000c004b0069006e0065006300740200000186000001060000030c00000261000000010000010f000002f4fc0200000003fb0000001e0054006f006f006c002000500072006f00700065007200740069006500730100000041000000780000000000000000fb0000000a00560069006500770073010000003d000002f4000000a400fffffffb0000001200530065006c0065006300740069006f006e010000025a000000b200000000000000000000000200000490000000a9fc0100000001fb0000000a00560069006500770073030000004e00000080000002e10000019700000003000004420000003efc0100000002fb0000000800540069006d00650100000000000004420000000000000000fb0000000800540069006d00650100000000000004500000000000000000000002cb000002f400000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000
  Selection:
    collapsed: false
  Tool Properties:
    collapsed: false
  Views:
    collapsed: false
  Width: 1340
  X: 72
  Y: 60

RViz 配置文件说明

  • Panels: 定义了RViz中的不同面板,包括显示面板、选择面板、工具属性面板和视图面板。
  • Visualization Manager: 配置了RViz的显示管理器,包括网格、TF、机器人模型等显示元素。
  • Tools: 列出了RViz中可用的工具,如相机移动、选择、测量、设置初始姿态和设置目标等。
  • Transformation: 配置了当前的变换管理器(TF)。
  • Views: 定义了当前视图设置,如轨道视图。
  • Window Geometry: 设置了RViz窗口的几何属性,如高度、宽度和面板折叠状态。

详细说明

  1. Panels
  • Displays Panel: 显示当前的所有可视化对象,如网格、TF、机器人模型等。
    包括全局选项、状态、TF、机器人模型等树形结构展开设置。
  • Selection Panel: 用于选择和高亮显示RViz中的对象。
  • Tool Properties Panel: 显示当前选中工具的属性。
  • Views Panel: 显示和管理当前的视图设置。
  • Visualization Manager
    Grid: 显示网格,帮助定位和参考。
  • TF: 显示TF树,用于查看各坐标系之间的关系。
  1. RobotModel: 显示机器人模型,用于查看和调试机器人状态。
    Tools
  • Interact: 用于与RViz中的对象交互。
  • MoveCamera: 移动相机以调整视角。
  1. Select: 选择对象。
  • FocusCamera: 聚焦相机到选中对象。
  • Measure: 测量工具。

3 发布状态

现在我们需要一种方法来指定机器人处于什么状态。为此,我们必须指定所有三个关节和整体里程表。

在second_ros2_ws/src/urdf_tutorial_r2d2/urdf_tutorial_r2d2/ 目录下新增文件 state_publisher.py

如下图所示:
在这里插入图片描述

文件代码如下:

from math import sin, cos, pi
import rclpy
from rclpy.node import Node
from rclpy.qos import QoSProfile
from geometry_msgs.msg import Quaternion
from sensor_msgs.msg import JointState
from tf2_ros import TransformBroadcaster, TransformStamped

class StatePublisher(Node):

    def __init__(self):
        rclpy.init()
        super().__init__('state_publisher')

        qos_profile = QoSProfile(depth=10)
        self.joint_pub = self.create_publisher(JointState, 'joint_states', qos_profile)
        self.broadcaster = TransformBroadcaster(self, qos=qos_profile)
        self.nodeName = self.get_name()
        self.get_logger().info("{0} started".format(self.nodeName))

        degree = pi / 180.0
        loop_rate = self.create_rate(30)

        # robot state
        tilt = 0.
        tinc = degree
        swivel = 0.
        angle = 0.
        height = 0.
        hinc = 0.005

        # message declarations
        odom_trans = TransformStamped()
        odom_trans.header.frame_id = 'odom'
        odom_trans.child_frame_id = 'axis'
        joint_state = JointState()

        try:
            while rclpy.ok():
                rclpy.spin_once(self)

                # update joint_state
                now = self.get_clock().now()
                joint_state.header.stamp = now.to_msg()
                joint_state.name = ['swivel', 'tilt', 'periscope']
                joint_state.position = [swivel, tilt, height]

                # update transform
                # (moving in a circle with radius=2)
                odom_trans.header.stamp = now.to_msg()
                odom_trans.transform.translation.x = cos(angle)*2
                odom_trans.transform.translation.y = sin(angle)*2
                odom_trans.transform.translation.z = 0.7
                odom_trans.transform.rotation = \
                    euler_to_quaternion(0, 0, angle + pi/2) # roll,pitch,yaw

                # send the joint state and transform
                self.joint_pub.publish(joint_state)
                self.broadcaster.sendTransform(odom_trans)

                # Create new robot state
                tilt += tinc
                if tilt < -0.5 or tilt > 0.0:
                    tinc *= -1
                height += hinc
                if height > 0.2 or height < 0.0:
                    hinc *= -1
                swivel += degree
                angle += degree/4

                # This will adjust as needed per iteration
                loop_rate.sleep()

        except KeyboardInterrupt:
            pass

def euler_to_quaternion(roll, pitch, yaw):
    qx = sin(roll/2) * cos(pitch/2) * cos(yaw/2) - cos(roll/2) * sin(pitch/2) * sin(yaw/2)
    qy = cos(roll/2) * sin(pitch/2) * cos(yaw/2) + sin(roll/2) * cos(pitch/2) * sin(yaw/2)
    qz = cos(roll/2) * cos(pitch/2) * sin(yaw/2) - sin(roll/2) * sin(pitch/2) * cos(yaw/2)
    qw = cos(roll/2) * cos(pitch/2) * cos(yaw/2) + sin(roll/2) * sin(pitch/2) * sin(yaw/2)
    return Quaternion(x=qx, y=qy, z=qz, w=qw)

def main():
    node = StatePublisher()

if __name__ == '__main__':
    main()

代码说明:

  1. 导入必要的库:
from math import sin, cos, pi
import rclpy
from rclpy.node import Node
from rclpy.qos import QoSProfile
from geometry_msgs.msg import Quaternion
from sensor_msgs.msg import JointState
from tf2_ros import TransformBroadcaster, TransformStamped

  1. 定义StatePublisher类:
class StatePublisher(Node):
    def __init__(self):
        rclpy.init()
        super().__init__('state_publisher')
        qos_profile = QoSProfile(depth=10)
        self.joint_pub = self.create_publisher(JointState, 'joint_states', qos_profile)
        self.broadcaster = TransformBroadcaster(self, qos=qos_profile)
        self.nodeName = self.get_name()
        self.get_logger().info("{0} started".format(self.nodeName))

  1. 初始化参数和变量:
        degree = pi / 180.0
        loop_rate = self.create_rate(30)

        tilt = 0.
        tinc = degree
        swivel = 0.
        angle = 0.
        height = 0.
        hinc = 0.005

  1. 声明消息类型:
        odom_trans = TransformStamped()
        odom_trans.header.frame_id = 'odom'
        odom_trans.child_frame_id = 'axis'
        joint_state = JointState()

  1. 主循环:
        try:
            while rclpy.ok():
                rclpy.spin_once(self)

                now = self.get_clock().now()
                joint_state.header.stamp = now.to_msg()
                joint_state.name = ['swivel', 'tilt', 'periscope']
                joint_state.position = [swivel, tilt, height]

                odom_trans.header.stamp = now.to_msg()
                odom_trans.transform.translation.x = cos(angle)*2
                odom_trans.transform.translation.y = sin(angle)*2
                odom_trans.transform.translation.z = 0.7
                odom_trans.transform.rotation = euler_to_quaternion(0, 0, angle + pi/2)

                self.joint_pub.publish(joint_state)
                self.broadcaster.sendTransform(odom_trans)

                tilt += tinc
                if tilt < -0.5 or tilt > 0.0:
                    tinc *= -1
                height += hinc
                if height > 0.2 or height < 0.0:
                    hinc *= -1
                swivel += degree
                angle += degree/4

                loop_rate.sleep()
        except KeyboardInterrupt:
            pass

  1. 欧拉角转四元数函数:
def euler_to_quaternion(roll, pitch, yaw):
    qx = sin(roll/2) * cos(pitch/2) * cos(yaw/2) - cos(roll/2) * sin(pitch/2) * sin(yaw/2)
    qy = cos(roll/2) * sin(pitch/2) * cos(yaw/2) + sin(roll/2) * cos(pitch/2) * sin(yaw/2)
    qz = cos(roll/2) * cos(pitch/2) * sin(yaw/2) - sin(roll/2) * sin(pitch/2) * cos(yaw/2)
    qw = cos(roll/2) * cos(pitch/2) * cos(yaw/2) + sin(roll/2) * sin(pitch/2) * sin(yaw/2)
    return Quaternion(x=qx, y=qy, z=qz, w=qw)

  1. 主函数
def main():
    node = StatePublisher()

if __name__ == '__main__':
    main()


4 创建启动文件

创建一个新second_ros2_ws/src/urdf_tutorial_r2d2/launch文件夹。

mkdir -p launch

在这里插入图片描述

打开编辑器并粘贴以下代码,将其保存为second_ros2_ws/src/urdf_tutorial_r2d2/launch/demo.launch.py

代码如下:

import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node

def generate_launch_description():

    use_sim_time = LaunchConfiguration('use_sim_time', default='false')

    urdf_file_name = 'r2d2.urdf.xml'
    urdf = os.path.join(
        get_package_share_directory('urdf_tutorial_r2d2'),
        urdf_file_name)
    with open(urdf, 'r') as infp:
        robot_desc = infp.read()

    return LaunchDescription([
        DeclareLaunchArgument(
            'use_sim_time',
            default_value='false',
            description='Use simulation (Gazebo) clock if true'),
        Node(
            package='robot_state_publisher',
            executable='robot_state_publisher',
            name='robot_state_publisher',
            output='screen',
            parameters=[{'use_sim_time': use_sim_time, 'robot_description': robot_desc}],
            arguments=[urdf]),
        Node(
            package='urdf_tutorial_r2d2',
            executable='state_publisher',
            name='state_publisher',
            output='screen'),
    ])

5 编辑setup.py文件

您必须告诉colcon构建工具如何安装 Python 包。second_ros2_ws/src/urdf_tutorial_r2d2/setup.py按如下方式编辑文件:

包括这些导入语句

import os
from glob import glob
from setuptools import setup
from setuptools import find_packages

添加以下两行data_files

data_files=[
  ...
  (os.path.join('share', package_name, 'launch'), glob(os.path.join('launch', '*launch.[pxy][yma]*'))),
  (os.path.join('share', package_name), glob('urdf/*')),
],

添加的代码位置如下:

在这里插入图片描述

保存setup.py更改后的文件


6 安装/编译 软件包

cd second_ros2_ws
colcon build --symlink-install --packages-select urdf_tutorial_r2d2

获取安装文件:

source install/setup.bash

执行结果如下:

在这里插入图片描述

7 查看结果

启动包

ros2 launch urdf_tutorial_r2d2 demo.launch.py

运行后报错:

在这里插入图片描述
查看是因为launch.py 文件中urdf 文件名定义的后缀有问题
在这里插入图片描述
重新修改文件名再重新编译

在这里插入图片描述

重新再启动包

运行结果如下:

在这里插入图片描述
打开一个新终端,使用以下命令运行 Rviz
新增命令窗口:

rviz2 -d second_ros2_ws/install/urdf_tutorial_r2d2/share/urdf_tutorial_r2d2/r2d2.rviz

运行效果:

在这里插入图片描述

  • 31
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小海聊智造

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值