コンテンツにスキップ

04 · Python でロボットを動かす(Hello Robot)

⏱ 20 分 · レベル:初級 · スクリプト:isaac/04_hello_robot.py

目標: ROS もグラフも使わずに、Python スクリプトから Lime の車輪、アーム、グリッパーを直接制御します。これはいろいろ試すのに最も手早い方法で、強化学習やテストのスクリプトがロボットとやりとりするときの方法でもあります。

0.6 m 前進し、左に 90° 旋回し、アームを伸ばし、グリッパーを開いて閉じ、アームを折りたたみます。

考え方

アーティキュレーション: Isaac Sim のロボットはアーティキュレーション(articulation)です。アーティキュレーションとは、ジョイントでつながった剛体のリンクのツリーで、まとめてシミュレーションされます。Articulation(path_of_the_root) を使うと、そのすべての DoF(自由度、つまり動かせるジョイント)にまとめてアクセスできます。

robot = Articulation("/World/turtlebot3_lime/Geometry/base_footprint/base_link")
robot.dof_names    # ['wheel_left_joint', 'wheel_right_joint', 'joint1', ..., 'gripper_right_joint']
wheels = robot.get_dof_indices(["wheel_left_joint", "wheel_right_joint"])
やりたいこと 呼び出し 使われるドライブ(チュートリアル 03 で設定)
車輪の速度 set_dof_velocity_targets([[wl, wr]], dof_indices=wheels) 速度ドライブ(減衰)
アーム / グリッパーの位置 set_dof_position_targets([[...]], dof_indices=arm)(少しずつ動かします。下を参照) 位置ドライブ(剛性 + 減衰)
状態を読む get_dof_positions()、get_dof_velocities()、get_world_poses()

角度はラジアン、直動ジョイント(グリッパー)はメートルで表します。

Python で差動二輪駆動: isaacsim.robot.experimental.wheeled_robots の DifferentialController は、チュートリアル 06 のグラフのノードと同じ式を計算します。

controller = DifferentialController(wheel_radius=0.06, wheel_base=0.29425)
wheel_speeds = controller.forward(np.array([0.2, 0.0]))   # 0.2 m/s forward -> [3.33, 3.33] rad/s
robot.set_dof_velocity_targets([wheel_speeds], dof_indices=wheels)

実行してみる

source scripts/isaac_env.sh
python isaac/04_hello_robot.py
python isaac/04_hello_robot.py --headless --test

スクリプトは、時刻ごとに動作を決めた小さなプログラムを実行します。

program = [
    (0.5, lambda: drive(0.2, 0.0)),                          # forward 0.2 m/s for 3 s -> 0.6 m
    (3.5, lambda: drive(0.0, math.pi / 2 / 2.0)),            # turn left: 90 deg in 2 s
    (5.5, lambda: drive(0.0, 0.0)),
    (6.0, lambda: move_arm(REACH)),                          # smoothly, in 1.5 s (see below)
    (8.0, lambda: robot.set_dof_position_targets([[0.019]], dof_indices=gripper)),   # open
    (9.0, lambda: robot.set_dof_position_targets([[-0.010]], dof_indices=gripper)),  # close
    (10.0, lambda: move_arm(lime.ARM_HOME)),
]
[04][check] ok   drove 0.58 m forward (commanded 0.6 m)
[04][check] ok   turned left to 84.2 deg (commanded 90)
[04][check] ok   arm reached the reach pose (max error 0.002 rad)
[04][check] ok   gripper opened to 0.0190 m
[04][check] ok   base stayed flat on the floor while the arm moved (max tilt 0.0 deg)
[04][test] PASS

指令値とのわずかな差は、加速によるものです。ロボットが指令された速度に達するまでには、少し時間がかかります。

アームは一気に動かさず、なめらかに動かす

robot.set_dof_position_targets([REACH], dof_indices=arm) のように、アームを目標へ直接送ることもできます。すると位置ドライブは、アームをサーボの最高速度(約 4.7 rad/s)で振り、動き出しも停止も一瞬で行います。その反動でロボット全体が傾きます。Lime の車輪は前寄りにあり、重心は車軸のわずか約 4 cm 後ろにあるので、後部が床から浮き上がります。測定結果は次のとおりです。

アームの動かし方 台車の最大の傾き
目標へ一気に(サーボの最高速度) 伸ばすとき 19.6°、折りたたむとき 46.7°
同じ動かし方で、バッテリーの質量を 2 倍の 3 kg にした場合 伸ばすとき 1.4°、折りたたむとき 16.7°
速度を 1 rad/s に制限 0.5°
1.5 s かけてなめらかに (move_arm) 0.04°

実際のアームのコントローラーも、目標へ一気に飛ぶことはありません。MoveIt(チュートリアル 12)は、速度と加速度の制限を守る軌道を計画します。move_arm はその最も単純な版です。毎フレーム目標を少しずつ動かし、動き出しと停止をなめらかにします。

arm_motion = None  # (start time, duration, start angles, target angles)


def move_arm(target, seconds=1.5):
    """Move the arm SMOOTHLY to `target` in `seconds`, like a real arm controller (MoveIt in tutorial 12).

    Never jump the position target: the drives then swing the arm at full servo speed (~4.7 rad/s), and the
    reaction tips the whole robot onto its nose - the wheels are near the front and the base's centre of mass
    is only ~4 cm behind the wheel axle (measured: up to 47 deg)."""
    global arm_motion
    arm_motion = (steps / 60.0, seconds, robot.get_dof_positions(dof_indices=arm).numpy()[0].copy(), np.array(target))


def update_arm(t):
    if arm_motion:
        t0, duration, start, target = arm_motion
        a = min(1.0, (t - t0) / duration)
        a = 0.5 - 0.5 * math.cos(math.pi * a)  # 0 -> 1 with a smooth start and stop
        robot.set_dof_position_targets([list(start + a * (target - start))], dof_indices=arm)

指令を出すのは左のグリッパーの指だけです

gripper_right_joint は、mimic ジョイント(チュートリアル 03)によって自動的に gripper_left_joint に追従します。

スクリプト全体:isaac/04_hello_robot.py
# SPDX-FileCopyrightText: 2026 An (an-robotics)
# SPDX-License-Identifier: Apache-2.0

"""Tutorial 04 - Move TurtleBot3 Lime from Python ("Hello Robot").

    source scripts/isaac_env.sh
    python isaac/04_hello_robot.py
    python isaac/04_hello_robot.py --headless --test

No ROS, no graphs: the script talks to the robot directly through the Articulation API.
  * wheels  : a DifferentialController turns (forward speed, turn rate) into wheel speeds
              -> set_dof_velocity_targets()
  * arm     : joint angles -> set_dof_position_targets(), moved smoothly (never jump: see move_arm)
  * gripper : finger position -> set_dof_position_targets() (the second finger follows by itself)

The program: drive 0.6 m forward, turn 90 deg left, raise the arm, open and close the gripper, fold the arm.
"""

import math
import sys

from common.cli import parse_args

args = parse_args(__doc__.splitlines()[0])

from isaacsim import SimulationApp

simulation_app = SimulationApp({"headless": args.headless, "width": 1280, "height": 720})

import isaacsim.core.experimental.utils.app as app_utils
import isaacsim.core.experimental.utils.stage as stage_utils
import numpy as np
from common import lime
from isaacsim.core.experimental.objects import GroundPlane
from isaacsim.core.experimental.prims import Articulation
from isaacsim.core.simulation_manager import SimulationManager
from pxr import UsdLux

app_utils.enable_extension("isaacsim.robot.experimental.wheeled_robots")
from isaacsim.robot.experimental.wheeled_robots import DifferentialController

stage = stage_utils.create_new_stage(template="sunlight")
UsdLux.DomeLight.Define(stage, "/World/DomeLight").GetIntensityAttr().Set(500.0)
GroundPlane("/World/GroundPlane")
articulation_root = lime.add_lime("/World/turtlebot3_lime")

recorder = None
if args.record:
    from common.recorder import Recorder

    recorder = Recorder(args.record, eye=(0.2, -1.6, 1.0), target=(0.5, 0.2, 0.2), every_n=3, fps=20)

SimulationManager.setup_simulation(dt=1.0 / 60.0)
app_utils.play()
simulation_app.update()

# --- The robot and its joints --------------------------------------------------------------------------------
robot = Articulation(articulation_root)
print(f"[04] {robot.num_dofs} DoF: {robot.dof_names}", flush=True)
wheels = robot.get_dof_indices(lime.WHEEL_JOINTS)
arm = robot.get_dof_indices(lime.ARM_JOINTS)
gripper = robot.get_dof_indices([lime.GRIPPER_JOINT])

controller = DifferentialController(wheel_radius=lime.WHEEL_RADIUS, wheel_base=lime.WHEEL_BASE)

REACH = [0.0, -0.6, 0.3, 0.0, 1.2, 0.0]  # rad: reach forward


def drive(v, w):
    """v: forward speed [m/s], w: turn rate [rad/s] (positive = left)."""
    robot.set_dof_velocity_targets([controller.forward(np.array([v, w]))], dof_indices=wheels)


def yaw():
    w_, x_, y_, z_ = robot.get_world_poses()[1].numpy()[0]
    return math.atan2(2 * (w_ * z_ + x_ * y_), 1 - 2 * (y_ * y_ + z_ * z_))


def tilt():
    """How far the base leans (roll or pitch, degrees): 0 = flat on the floor."""
    w_, x_, y_, z_ = robot.get_world_poses()[1].numpy()[0]
    up_z = 1 - 2 * (x_ * x_ + y_ * y_)  # the z component of the robot's "up" axis
    return math.degrees(math.acos(max(-1.0, min(1.0, up_z))))


arm_motion = None  # (start time, duration, start angles, target angles)


def move_arm(target, seconds=1.5):
    """Move the arm SMOOTHLY to `target` in `seconds`, like a real arm controller (MoveIt in tutorial 12).

    Never jump the position target: the drives then swing the arm at full servo speed (~4.7 rad/s), and the
    reaction tips the whole robot onto its nose - the wheels are near the front and the base's centre of mass
    is only ~4 cm behind the wheel axle (measured: up to 47 deg)."""
    global arm_motion
    arm_motion = (steps / 60.0, seconds, robot.get_dof_positions(dof_indices=arm).numpy()[0].copy(), np.array(target))


def update_arm(t):
    if arm_motion:
        t0, duration, start, target = arm_motion
        a = min(1.0, (t - t0) / duration)
        a = 0.5 - 0.5 * math.cos(math.pi * a)  # 0 -> 1 with a smooth start and stop
        robot.set_dof_position_targets([list(start + a * (target - start))], dof_indices=arm)


# A tiny "program": (start time [s], action)
program = [
    (0.5, lambda: drive(0.2, 0.0)),  # forward 0.2 m/s for 3 s  -> 0.6 m
    (3.5, lambda: drive(0.0, math.pi / 2 / 2.0)),  # turn left: 90 deg in 2 s
    (5.5, lambda: drive(0.0, 0.0)),
    (6.0, lambda: move_arm(REACH)),
    (8.0, lambda: robot.set_dof_position_targets([[lime.GRIPPER_OPEN]], dof_indices=gripper)),
    (9.0, lambda: robot.set_dof_position_targets([[lime.GRIPPER_CLOSED]], dof_indices=gripper)),
    (10.0, lambda: move_arm(lime.ARM_HOME)),
]
log = {"tilt": 0.0}
steps = 0
while simulation_app.is_running():
    t = steps / 60.0
    while program and t >= program[0][0]:
        program.pop(0)[1]()
    update_arm(t)
    simulation_app.update()
    steps += 1
    log["tilt"] = max(log["tilt"], tilt())
    if recorder:
        recorder.capture()
    if steps == int(3.5 * 60):
        log["after_forward"] = robot.get_world_poses()[0].numpy()[0, :2].copy()
    if steps == int(5.9 * 60):
        log["yaw_after_turn"] = math.degrees(yaw())
    if steps == int(7.9 * 60):
        log["arm_reach"] = robot.get_dof_positions(dof_indices=arm).numpy()[0].copy()
    if steps == int(8.9 * 60):
        log["gripper_open"] = float(robot.get_dof_positions(dof_indices=gripper).numpy()[0, 0])
    if (args.test or args.record) and t > 12.0:
        break

ok = True
if args.test:
    arm_err = float(np.max(np.abs(log["arm_reach"] - np.array(REACH))))
    checks = {
        f"drove {log['after_forward'][0]:.2f} m forward (commanded 0.6 m)": abs(log["after_forward"][0] - 0.6) < 0.06,
        f"turned left to {log['yaw_after_turn']:.1f} deg (commanded 90)": abs(log["yaw_after_turn"] - 90.0) < 8.0,
        f"arm reached the reach pose (max error {arm_err:.3f} rad)": arm_err < 0.05,
        f"gripper opened to {log['gripper_open']:.4f} m": log["gripper_open"] > 0.015,
        f"base stayed flat on the floor while the arm moved (max tilt {log['tilt']:.1f} deg)": log["tilt"] < 2.0,
    }
    for text, passed in checks.items():
        print(f"[04][check] {'ok  ' if passed else 'FAIL'} {text}")
    ok = all(checks.values())
    print(f"[04][test] {'PASS' if ok else 'FAIL'}")
if recorder:
    recorder.save()
app_utils.stop()
simulation_app.close(exit_code=0 if ok else 1)
sys.exit(0 if ok else 1)

次へ: 05 · はじめての Action Graph