Skip to content

13 · Pick and place

⏱ 45 min · Level: intermediate · Script: isaac/13_all_together.py · ROS: lime_full.launch.py, mission

Goal. Run the complete simulated TurtleBot3 Lime, with every sensor and graph from tutorials 06–12 plus MoveIt 2, Nav2 and YOLO at the same time. Then give it a job: find the banana, pick it up, put it into the bowl, and park. You'll see how the pieces connect: a 2D detection becomes a 3D position, the robot drives up to it precisely, and the arm grasps it.

The mission: YOLO and the depth camera find the banana, the Lime drives up to it, MoveIt picks it up, the robot carries it to the bowl and drops it in, then Nav2 parks the robot in the far corner.

The whole system

flowchart LR
  subgraph ISAAC["Isaac Sim · isaac/13_all_together.py"]
    direction TB
    g06[clock + drive<br/>06]
    g07[odom + TF + joint states<br/>07 / 12]
    g08[camera: RGB + depth<br/>08]
    g09[LiDAR + IMU<br/>09]
    g12[joint commands<br/>12]
  end
  subgraph ROS["ROS 2 · lime_full.launch.py"]
    direction TB
    rc[ros2_control + MoveIt 2<br/>lime_isaac_moveit]
    nav[Nav2<br/>map, AMCL, planner, controller]
    yolo[YOLO<br/>lime_yolo]
    mission[mission<br/>lime_isaac_bringup]
  end
  g06 -- "/clock" --> ROS
  nav -- "/cmd_vel" --> g06
  mission -- "/cmd_vel (last centimetres)" --> g06
  g07 -- "/odom /tf /isaac_joint_states" --> rc & nav & mission
  rc -- "/isaac_joint_commands" --> g12
  g08 -- "color/image_raw" --> yolo
  g08 -- "aligned_depth_to_color, camera_info" --> mission
  g09 -- "/scan" --> nav
  yolo -- "/detections" --> mission
  mission -- "MoveGroup, GripperCommand" --> rc
  mission -- NavigateToPose --> nav

One robot_state_publisher

lime_full.launch.py includes lime_isaac_moveit/moveit.launch.py, which brings the one and only robot_state_publisher. Its URDF also contains the ros2_control block. Nav2's bringup is included directly, without navigation.launch.py, so a second robot_state_publisher never starts. /joint_states comes only from joint_state_broadcaster (see tutorial 12).

Objects you can pick up

In tutorials 08–10 the objects on the floor are only pictures for the camera: they have no collider and no mass. Here they are real (add_object_physics): colliders and mass, so the robot cannot drive through them, and they would be knocked over if it drove into them. Picking one up needs two more things: a bowl the banana fits into, and grippy fingers.

Object Physics Why
banana rigid body, 66 g, convex decomposition collider it must fall, be pushed and be lifted. A single convex hull would turn the curved banana into a blob 7 cm wide, too wide for the gripper
mug, mustard bottle rigid bodies, 118 g and 603 g; convex decomposition for the mug, convex hull for the bottle they would be knocked over if the robot drove into them. With the default convex hull the mug crept 16 cm across the floor by itself in 5 s; with a convex decomposition it stands still
bowl static collider, none (the exact triangle mesh), and in this tutorial 1.5× bigger it must hold the banana in its hollow; the 19 cm banana does not fit in the original 16 cm bowl
fingers + banana physics material, friction 1.0 (this tutorial) rubber-like pads, so a 10 N squeeze holds the banana

Open assets/scenes/lime_room.usda, then use the Property panel's + Add button:

  1. Select /World/LimeRoom/Objects/Banana. Choose + Add ▸ Physics ▸ Rigid Body with Colliders Preset, then + Add ▸ Physics ▸ Mass, and set Mass to 0.066. Do the same for the Mug (0.118) and the Bottle (0.603). The bottle can keep its Convex Hull; give the mug's mesh Convex Decomposition too (step 2).
  2. Expand the banana in the Stage panel and select its mesh. The preset gave it a Convex Hull collider. Change Approximation to Convex Decomposition.

    The banana's mesh: the Collider section after the preset

  3. Select the bowl. Set Scale to 1.5 and Translate Z to 0.044, so it still stands on the floor. Then choose + Add ▸ Physics ▸ Colliders Preset: a static collider with approximation None (the triangle mesh itself), which is allowed for an object that never moves.

  4. Create ▸ Physics ▸ Physics Material, tick Rigid Body Material and click Ok. Set its static and dynamic friction to 1.0. Select the banana's mesh again and pick the new material in its Physics materials on selected models section (this section appears on collider prims only).

The fingers need the same material, but the robot's finger colliders (gripper_left_palm, gripper_right_palm) are instanced: shared, read-only copies that the GUI cannot change. The Python version binds the material one level up, on gripper_left_link and gripper_right_link, and the binding applies to every collider below them.

![Create ▸ Physics ▸ Physics Material asks for the material type](../assets/img/gui/13_physics_material.png){ .full }

Press Play and drag the banana with Shift + left mouse: it now falls and tumbles.

To keep your work, press Stop ■ and save it with File ▸ Save As my_stages/13_pick_and_place.usd, not over lime_room.usda: the GUI tabs of tutorials 08 and 11 open that file.

13_all_together.py builds the lime_room with object_physics=True:

add_object_physics(): colliders and mass for every object
def add_object_physics(stage, root: str = "/World/LimeRoom"):
    """Make the objects real: colliders and mass, so the robot cannot drive through them (tutorial 13).

    Without this (tutorials 08-10) they are only pictures for the camera. With it:
      * banana, mug, bottle: rigid bodies with their real (YCB) masses: they fall, can be pushed, knocked over
        and lifted. Colliders: a convex decomposition for the banana (a single convex hull would make the
        curved banana a 7 cm wide blob, too wide for the gripper) and for the mug (with a convex hull it crept
        across the floor by itself); a convex hull for the bottle.
      * bowl: a static collider (it never moves) that keeps its exact, hollow shape ("none" = the triangle mesh
        itself, which PhysX allows for static objects only)
    """
    from pxr import PhysxSchema, Usd, UsdGeom, UsdPhysics

    def colliders(prim, approximation):
        for p in Usd.PrimRange(prim):
            if p.IsA(UsdGeom.Mesh):
                UsdPhysics.CollisionAPI.Apply(p)
                UsdPhysics.MeshCollisionAPI.Apply(p).CreateApproximationAttr(approximation)

    for name, mass, approximation in (
        ("Banana", 0.066, "convexDecomposition"),
        ("Mug", 0.118, "convexDecomposition"),
        ("Bottle", 0.603, "convexHull"),
    ):
        prim = stage.GetPrimAtPath(f"{root}/Objects/{name}")
        UsdPhysics.RigidBodyAPI.Apply(prim)
        UsdPhysics.MassAPI.Apply(prim).CreateMassAttr(mass)  # kg
        colliders(prim, approximation)
    # a banana squeezed between two fingers (tutorial 13) needs more solver iterations
    banana = stage.GetPrimAtPath(f"{root}/Objects/Banana")
    PhysxSchema.PhysxRigidBodyAPI.Apply(banana).CreateSolverPositionIterationCountAttr(32)
    colliders(stage.GetPrimAtPath(f"{root}/Objects/Bowl"), "none")

and then calls one extra function for the bowl and the fingers:

BOWL_SCALE = 1.5  # tutorial 13: the 19 cm banana fits into a 24 cm bowl, not into the 16 cm original


def setup_pick_and_place(stage, robot_path: str, root: str = "/World/LimeRoom"):
    """Tutorial 13, on top of add_object_physics(): a bowl the banana fits into, and grippy fingers.
      * bowl: 1.5x bigger (its static collider scales with it)
      * fingers and banana: rubber-like friction 1.0, so a 10 N squeeze holds the banana
    """
    from isaacsim.core.experimental.prims import XformPrim
    from pxr import Usd, UsdPhysics, UsdShade

    _name, _asset, x, y, _yaw, half_height, _up, _coco = next(o for o in OBJECTS if o[0] == "Bowl")
    bowl = XformPrim(f"{root}/Objects/Bowl")
    bowl.set_local_scales([[BOWL_SCALE] * 3])
    _position, orientation = bowl.get_world_poses()
    bowl.set_world_poses(positions=[[x, y, BOWL_SCALE * half_height + 0.002]], orientations=orientation)

    rubber = UsdShade.Material.Define(stage, f"{root}/PhysicsMaterials/rubber")
    api = UsdPhysics.MaterialAPI.Apply(rubber.GetPrim())
    api.CreateStaticFrictionAttr(1.0)
    api.CreateDynamicFrictionAttr(1.0)
    banana = stage.GetPrimAtPath(f"{root}/Objects/Banana")
    fingers = [p for p in Usd.PrimRange(stage.GetPrimAtPath(robot_path)) if p.GetName() in ("gripper_left_link", "gripper_right_link")]
    for prim in [banana, *fingers]:
        UsdShade.MaterialBindingAPI.Apply(prim).Bind(rubber, UsdShade.Tokens.weakerThanDescendants, "physics")

Run it

Terminal 1, Isaac Sim:

source scripts/isaac_env.sh
python isaac/13_all_together.py

Terminal 2, the ROS 2 stack and RViz (wait for "Managed nodes are active" and "You can start planning now!"; add rviz:=false to leave RViz out):

./scripts/build_ws.sh
./docker/run_ros.sh ros2 launch lime_isaac_bringup lime_full.launch.py

Terminal 3, the mission (the first start downloads yolo11m.pt, about 40 MB, in terminal 2):

./docker/run_ros.sh ros2 run lime_isaac_bringup mission
YOLO: banana (0.88) at (0.75, -0.11), bowl (0.70) at (0.96, 0.41)
YOLO: banana (0.92) at (0.792, -0.123), pointing 19 deg
MoveIt: above the banana: done
MoveIt: down to the banana: done
MoveIt: lift: done
MoveIt: carry: done
YOLO: bowl (0.67) at (0.998, 0.377), radius 9 cm
MoveIt: above the bowl: done
MoveIt: arm folded: done
Nav2: parking at (2.8, -1.8)
mission complete: the banana is in the bowl

In the simulation the banana really is at (0.800, −0.121), pointing 20°, and the bowl at (1.0, 0.4). The first look, from the start, is 5 cm short. The second look, from the side, is within 1 cm, which is good enough to grasp.

The banana in the bowl, the arm folding

How the mission works

flowchart LR
  a["1 · YOLO + depth<br/>find banana and bowl"] --> b["2 · look again<br/>from the side"] --> c["3 · drive to 16 cm"]
  c --> d["4 · MoveIt<br/>pick"] --> e["5 · drive round the mug<br/>to the bowl"] --> f["6 · MoveIt<br/>place, fold"] --> g["7 · into the open<br/>Nav2 parks"]
The mission's main part: lime_isaac_bringup/scripts/mission.py
    # 1. Find the banana and the bowl from where we are (the banana is small and far: collect a few seconds).
    found, found_bowl = lime.locate("banana", seconds=6.0), lime.locate("bowl", seconds=2.0)
    if found is None or found_bowl is None:
        fail("YOLO: I need to see both the banana and the bowl")
    banana, _ = long_object(found)
    bowl, _ = round_object(found_bowl)
    log.info(f"YOLO: banana ({found['score']:.2f}) at ({banana[0]:.2f}, {banana[1]:.2f}), bowl ({found_bowl['score']:.2f}) at ({bowl[0]:.2f}, {bowl[1]:.2f})")

    # 2. From here we see the banana almost end-on: its far half hides behind its near half. Look again from
    #    45 cm away and 55 deg further round (the side away from the mug): now the whole banana is visible.
    x, y, _ = lime.pose()
    look = math.atan2(banana[1] - y, banana[0] - x) + math.radians(55)
    toward = np.array([math.cos(look), math.sin(look)])
    lime.drive_to(*(banana - 0.45 * toward))
    lime.turn_to(look)
    found = lime.locate("banana")
    if found is None:
        fail("YOLO: lost the banana")
    banana, banana_yaw = long_object(found)
    log.info(f"YOLO: banana ({found['score']:.2f}) at ({banana[0]:.3f}, {banana[1]:.3f}), pointing {math.degrees(banana_yaw) % 180:.0f} deg")

    # 3. Stop with the banana 16 cm in front of the robot: inside the arm's reach for a top-down grasp.
    lime.drive_to(*(banana - 0.16 * toward))
    lime.turn_to(look)

    # 4. Pick it up.
    lime.gripper(GRIPPER_OPEN)
    bx, by = lime.to_base(*banana)
    yaw = wrap(banana_yaw - lime.pose()[2])  # the banana's direction as seen from the robot
    above, grasp, lifted = (top_down_ik(bx, by, z, yaw) for z in (0.10, 0.03, 0.15))
    if None in (above, grasp, lifted):
        fail(f"the banana at ({bx:.3f}, {by:.3f}) in the robot frame is out of reach")
    if not (lime.move_arm(above, "above the banana") and lime.move_arm(grasp, "down to the banana")):
        fail("MoveIt: grasp failed")
    lime.gripper(GRIPPER_CLOSED)  # stops when the fingers touch the banana, and keeps squeezing
    if not (lime.move_arm(lifted, "lift") and lime.move_arm(CARRY, "carry")):
        fail("MoveIt: lift failed")

    # 5. Back to the bowl. The mug stands between the banana and the bowl, so go round: approach the bowl
    #    from its open side (from -y, 42 cm away), look again, and drive up until the bowl is 20 cm in front.
    lime.drive_to(bowl[0], bowl[1] - 0.42)
    lime.turn_to(math.pi / 2)
    found = lime.locate("bowl")
    if found is None:
        fail("YOLO: lost the bowl")
    bowl, radius = round_object(found)
    log.info(f"YOLO: bowl ({found['score']:.2f}) at ({bowl[0]:.3f}, {bowl[1]:.3f}), radius {radius * 100:.0f} cm")
    lime.drive_to(bowl[0], bowl[1] - 0.20)
    lime.turn_to(math.pi / 2)

    # 6. Put the banana in: above the bowl's centre, or as close to it as the arm reaches; banana across the robot.
    bx, by = lime.to_base(*bowl)
    release = next((q for x in np.arange(bx, 0.10, -0.005) if (q := top_down_ik(x, by, 0.13, math.pi / 2))), None)
    if release is None or not lime.move_arm(release, "above the bowl"):
        fail("MoveIt: could not reach the bowl")
    lime.gripper(GRIPPER_OPEN)
    lime.spin_for(1.0)
    lime.move_arm(HOME, "arm folded")

    # 7. Back away from the bowl and drive into the open middle of the room, then let Nav2 park the robot.
    #    (Started right next to the bottle, Nav2 would steer the robot straight through it.)
    x, y, yaw = lime.pose()
    lime.drive_to(x - 0.12 * math.cos(yaw), y - 0.12 * math.sin(yaw), backwards=True)
    lime.drive_to(bowl[0] + 0.6, bowl[1] - 0.45)
    log.info(f"Nav2: parking at ({PARK[0]}, {PARK[1]})")
    goal = PoseStamped()
    goal.header.frame_id = "map"
    goal.pose.position.x, goal.pose.position.y = PARK[0], PARK[1]
    goal.pose.orientation.w = 1.0
    lime.nav.goToPose(goal)
    while not lime.nav.isTaskComplete():
        time.sleep(0.2)
    if lime.nav.getResult() != TaskResult.SUCCEEDED:
        fail(f"Nav2: could not park: {lime.nav.getResult()}")

1. From a 2D box to 3D points

A bigger YOLO

lime_full.launch.py runs yolo11m.pt (medium) instead of tutorial 10's yolo11n.pt (nano). Seen from the low camera, the banana is a flat yellow crescent: the nano model calls it a frisbee (0.44), the small one a banana with 0.46, the medium one a banana with 0.88. (In tutorial 10 the nano model just finds the banana, with 0.40. Here the banana has physics and rests a few millimetres differently, and the nano model's answer tips over to frisbee.) The medium model takes about 75 ms per image on the CPU, which is fine at 5 images per second. Choose it with yolo_model:=....

YOLO says "banana, 0.9, in this box": pixels, not metres. The aligned depth image (tutorial 08) has, for every pixel \((u, v)\), the distance \(z\) along the camera's axis. The camera model from camera_info turns that into a 3D point in the camera's optical frame:

\[ x = \frac{(u - c_x)\,z}{f_x}, \qquad y = \frac{(v - c_y)\,z}{f_y}, \qquad z = z \]

TF then moves the points from camera_color_optical_frame into the odom frame, using the transform from the moment the image was taken (the detection's time stamp). The robot may have moved since then. Points on the floor (\(z \approx 0\)) are dropped. What is left is a small point cloud of the object.

Lime.locate()
    def locate(self, name, seconds=4.0):
        """Find object `name` with YOLO and measure where it is: a 3D point cloud of the object, in the odom frame.

        2D box (YOLO)  +  depth image  +  camera model  ->  3D points in the camera frame
                       +  TF odom <- camera at the image's time stamp  ->  3D points in the odom frame
        """
        self.detections.clear()
        self.spin_for(seconds)  # collect a few seconds of detections, keep the most confident one
        best = None
        for msg, depth_msg in self.detections:
            for d in msg.detections:
                h = d.results[0].hypothesis
                if h.class_id == name and (best is None or h.score > best[0]):
                    best = (h.score, d, msg.header, depth_msg)
        if best is None or self.K is None:
            return None
        score, det, header, depth_msg = best
        pts, camera = self.points(det, header, depth_msg)
        return None if pts is None else {"score": score, "points": pts, "camera": camera}

    def points(self, det, header, depth_msg):
        """The 3D points (odom frame) of one detection's box, and where the camera was. (None, None) if too few."""
        depth = np.frombuffer(depth_msg.data, dtype=np.float32).reshape(depth_msg.height, depth_msg.width)
        cx, cy = det.bbox.center.position.x, det.bbox.center.position.y
        w, h = det.bbox.size_x, det.bbox.size_y
        u0, u1 = int(max(cx - w / 2, 0)), int(min(cx + w / 2, depth_msg.width - 1))
        v0, v1 = int(max(cy - h / 2, 0)), int(min(cy + h / 2, depth_msg.height - 1))
        v, u = np.mgrid[v0:v1 + 1, u0:u1 + 1]
        z = depth[v0:v1 + 1, u0:u1 + 1]
        ok = np.isfinite(z) & (z > 0.05) & (z < 3.0)
        fx, fy, px, py = self.K[0, 0], self.K[1, 1], self.K[0, 2], self.K[1, 2]
        cam = np.stack([(u[ok] - px) * z[ok] / fx, (v[ok] - py) * z[ok] / fy, z[ok]], axis=1)  # optical frame
        tf = self.tf.lookup_transform("odom", header.frame_id, header.stamp, timeout=rclpy.duration.Duration(seconds=1.0))
        t, q = tf.transform.translation, tf.transform.rotation
        R = quat_to_matrix(q.x, q.y, q.z, q.w)
        pts = cam @ R.T + np.array([t.x, t.y, t.z])
        pts = pts[(pts[:, 2] > 0.006) & (pts[:, 2] < 0.40)]  # drop the floor (z = 0) around the object
        if len(pts) < 20:
            return None, None
        middle = np.median(pts[:, :2], axis=0)
        pts = pts[np.linalg.norm(pts[:, :2] - middle, axis=1) < 0.25]  # drop the background inside the box
        return pts, np.array([t.x, t.y])

2. Where exactly is it?

The camera sees only the front of an object, so each shape gets its own small rule:

  • Banana (a long object): its direction is the main axis of its points (principal component analysis), and the gripper closes across it. The grasp point is the middle of its length, halfway between the two ends. It is not simply the average point: the end nearer the camera gets more depth pixels and pulls the average towards it.
  • Bowl (a round object): the centre is not in the middle of the visible points, because those are all on the front. It lies one radius further along the line of sight, and the radius is half the visible width.
long_object() and round_object()
def long_object(found):
    """A lying object (the banana): its direction = the main axis of its points (PCA); the grasp point = the
    middle of its length. Not simply the average point: the end nearer the camera gets more depth pixels."""
    xy = found["points"][:, :2]
    mean = xy.mean(axis=0)
    eigenvalues, eigenvectors = np.linalg.eigh(np.cov((xy - mean).T))
    axis = eigenvectors[:, np.argmax(eigenvalues)]
    normal = np.array([-axis[1], axis[0]])
    along, across = (xy - mean) @ axis, (xy - mean) @ normal
    middle = (np.percentile(along, 2) + np.percentile(along, 98)) / 2  # halfway between the two ends
    at_middle = np.abs(along - middle) < 0.02  # the slice of the object there (a banana is curved)
    centre = mean + middle * axis + np.median(across[at_middle]) * normal
    return centre, math.atan2(axis[1], axis[0])


def round_object(found):
    """A round object (the bowl): the camera sees only its front, so centre = front surface + one radius
    further along the line of sight; the radius is half the width the camera sees."""
    xy = found["points"][:, :2]
    ray = np.median(xy, axis=0) - found["camera"]
    ray /= np.linalg.norm(ray)
    side = np.array([-ray[1], ray[0]])
    along, across = (xy - found["camera"]) @ ray, (xy - found["camera"]) @ side
    radius = (np.percentile(across, 98) - np.percentile(across, 2)) / 2
    front = np.percentile(along, 5)
    middle = (np.percentile(across, 98) + np.percentile(across, 2)) / 2
    return found["camera"] + (front + radius) * ray + middle * side, radius

3. The last centimetres: drive with odometry

Looking straight down, the arm reaches the floor only between about 12 and 20 cm in front of base_footprint. Nav2 stops within its goal tolerance of 25 cm, which is fine for parking but far too coarse for grasping. So for the short moves the mission drives itself: turn towards the target, drive in a straight line, and stop within a centimetre. It publishes /cmd_vel and reads the pose from TF (odom → base_footprint, Isaac Sim's odometry). Speed changes are gentle, because the robot may be carrying a banana.

Two rules keep this simple:

  • Look from the side, then drive blind. From the start the camera sees the banana almost end-on, and its far half hides behind its near half (the estimate was 5 cm short). So the robot looks again from 45 cm away and 55° further round. Then it drives the last 30 cm blind: close up, the low camera no longer sees the banana properly (at 16 cm the image's lower edge cuts it off), and Isaac Sim's odometry was within 3 mm of the truth after a 0.8 m drive in tutorial 07.
  • Go round the objects yourself. These short drives don't use Nav2, so nothing plans round the mug: the mission approaches the bowl from its open side.
  • Hand over to Nav2 in the open. After the drop the robot stands right next to the mustard bottle. Nav2 does see the bottle, but started that close to it, the first version of this mission drove straight through it. So the mission backs away from the bowl and drives 60 cm into the open middle of the room before Nav2 takes over.
turn_to(), drive_to(), to_base()
    def pose(self):
        """Robot pose (x, y, yaw) in the odom frame - Isaac Sim's odometry, through TF."""
        tf = self.tf.lookup_transform("odom", "base_footprint", rclpy.time.Time(), timeout=rclpy.duration.Duration(seconds=1.0))
        t, q = tf.transform.translation, tf.transform.rotation
        return t.x, t.y, math.atan2(2 * (q.w * q.z + q.x * q.y), 1 - 2 * (q.y * q.y + q.z * q.z))

    def send(self, v, w):
        msg = Twist()
        msg.linear.x, msg.angular.z = float(v), float(w)
        self.cmd.publish(msg)

    def turn_to(self, yaw):
        w, end = 0.0, time.time() + 30.0
        while time.time() < end:
            error = wrap(yaw - self.pose()[2])
            if abs(error) < 0.01:
                break
            target = math.copysign(min(0.5, max(0.08, 1.5 * abs(error))), error)
            w += max(-0.03, min(0.03, target - w))  # gentle acceleration: the robot carries things
            self.send(0.0, w)
            time.sleep(0.05)
        self.send(0.0, 0.0)
        time.sleep(0.5)

    def drive_to(self, x, y, backwards=False):
        """Turn towards (x, y) [odom frame], drive there in a straight line, stop within a centimetre."""
        px, py, _ = self.pose()
        heading = math.atan2(y - py, x - px) + (math.pi if backwards else 0.0)
        self.turn_to(heading)
        v, sign, end = 0.0, -1.0 if backwards else 1.0, time.time() + 60.0
        while time.time() < end:
            px, py, yaw = self.pose()
            ahead = (x - px) * math.cos(yaw) + (y - py) * math.sin(yaw)  # distance left along the heading
            if sign * ahead < 0.008:
                break
            target = min(0.12, max(0.02, 0.8 * abs(ahead)))
            v += max(-0.01, min(0.01, target - v))
            side = -(x - px) * math.sin(yaw) + (y - py) * math.cos(yaw)
            self.send(sign * v, max(-0.3, min(0.3, 2.0 * side * sign)) if abs(ahead) > 0.05 else 0.0)
            time.sleep(0.05)
        self.send(0.0, 0.0)
        time.sleep(0.5)

    def to_base(self, x, y):
        """odom-frame point -> base_footprint frame (where the arm works)."""
        px, py, yaw = self.pose()
        dx, dy = x - px, y - py
        return dx * math.cos(yaw) + dy * math.sin(yaw), -dx * math.sin(yaw) + dy * math.cos(yaw)

4. A top-down grasp: inverse kinematics on paper

For a grasp from straight above, the Lime's 6-joint arm becomes simple:

  • joint1 turns towards the object;
  • joint2 (shoulder) and joint3 (elbow) form a planar two-link arm with lengths \(L_1 = 12.4\) cm and \(L_2 = 10.45\) cm, which puts the wrist \(L_3 = 16.25\) cm above end_effector_link (the fingertips reach 2 cm lower still);
  • joint5 makes the three tilts add up to 180°, so the gripper points down;
  • joint6 turns the fingers across the banana.

With \(r\) = the horizontal distance and \(d_z\) = the height of the wrist above the shoulder, the law of cosines gives the elbow:

\[ \cos\theta_3 = \frac{r^2 + d_z^2 - L_1^2 - L_2^2}{2 L_1 L_2}, \qquad \theta_2 = \operatorname{atan2}(r, d_z) - \operatorname{atan2}(L_2 \sin\theta_3,\; L_1 + L_2 \cos\theta_3), \qquad \theta_5 = \pi - \theta_2 - \theta_3 \]

The mission computes these joint angles and gives them to MoveIt as joint goals. MoveIt still does the planning: a collision-free, smooth trajectory that respects the joint limits (the mission adds the floor to MoveIt's planning scene first). The grasp puts end_effector_link 10 cm above the floor, then down to 3 cm (the fingertips are then about 1 cm above the floor), closes the gripper, and lifts to 15 cm.

Grasp: above the banana, down and close, lift

Above the banana, down and close, lift. Two fingers pinching a curved banana act like a hinge, so the banana can swing as the arm moves (watch the video). It is still held firmly.

top_down_ik()
# The arm in the base_footprint frame (from the URDF): joint1 turns about a vertical axis at x = -0.024;
# joint2, joint3 and joint5 tilt the arm forward; joint4 and joint6 roll. Looking straight down, the arm is
# a planar 2-link arm (upper arm L1, forearm L2) plus L3 from the wrist to end_effector_link (the fingertips
# reach 2 cm further down).
SHOULDER_X, SHOULDER_Z = -0.024, 0.2065
L1, L2, L3 = 0.124, 0.1045, 0.1625


def top_down_ik(x, y, z, object_yaw):
    """Joint angles that put end_effector_link at (x, y, z) [base_footprint frame], pointing straight down,
    with the fingers closing across an object whose long axis points along object_yaw. None = out of reach."""
    j1 = math.atan2(y, x - SHOULDER_X)
    r = math.hypot(x - SHOULDER_X, y)  # horizontal distance from joint1's axis
    dz = z + L3 - SHOULDER_Z  # the wrist is L3 above end_effector_link
    c3 = (r * r + dz * dz - L1 * L1 - L2 * L2) / (2 * L1 * L2)  # law of cosines
    if abs(c3) > 1.0:
        return None
    j3 = math.acos(c3)  # elbow up
    j2 = math.atan2(r, dz) - math.atan2(L2 * math.sin(j3), L1 + L2 * math.cos(j3))
    j5 = math.pi - j2 - j3  # the three tilts add up to 180 deg: pointing down
    j6 = (j1 - object_yaw + math.pi / 2) % math.pi - math.pi / 2  # fingers across the object (either way round)
    joints = [j1, j2, j3, 0.0, j5, j6]
    limits = [(-2.82, 2.82), (-1.69, 1.76), (-1.75, 1.85), (-1.57, 1.57), (-1.66, 1.78), (-2.82, 2.82)]
    return joints if all(lo <= j <= hi for j, (lo, hi) in zip(joints, limits)) else None

Why not a pose goal?

MoveIt can solve inverse kinematics itself (kinematics.yaml, KDL). The Lime's MoveIt config uses position_only_ik: True, which ignores the gripper's orientation, so a "point straight down" pose goal would not be kept. For a top-down grasp the closed-form solution above is exact, instant, and easy to check.

5. Holding on

The gripper is told to close fully (−1 cm) and stops when the fingers touch the banana. The GripperActionController keeps commanding the closed position, so the position drive (tutorial 03: stiffness 1000 N/m, at most 10 N) keeps squeezing while the arm lifts and the robot drives.

The controller would finish the goal once it detects a stall: a finger velocity of almost zero for 2 s (allow_stalling: true in tutorial 12's ros2_controllers.yaml). In the simulation, though, a finger pressing against an object reports a velocity (about 0.3 m/s here) although its position does not change, so the stall is never detected. The mission therefore waits at most 3 s for the gripper and then carries on. The goal stays active, and the next gripper command (open, above the bowl) replaces it.

Automatic check

python isaac/13_all_together.py --headless --test follows the mission using the simulation's ground truth:

[13] ground truth: banana at [ 0.8   -0.121], bowl at [1.  0.4]
[13] banana lifted (10 cm above the floor) at t = 47 s
[13] banana in the bowl, 4.9 cm from its centre at t = 71 s
[13] arm folded at t = 73 s
[13] robot parked in the far corner at t = 98 s
[13][check] ok   banana picked up (more than 10 cm above the floor)
[13][check] ok   banana put into the bowl (within 7 cm of its centre)
[13][check] ok   arm folded afterwards
[13][check] ok   robot parked in the far corner (within 0.3 m)
[13][check] ok   banana still in the bowl at the end (4.9 cm from its centre)
[13][check] ok   mug not bumped into (moved 0.0 cm)
[13][check] ok   bottle not bumped into (moved 0.0 cm)
[13][test] PASS

The banana lands about 5 cm from the bowl's centre, short of it, because the stretched-out arm reaches only 18 cm in front of the robot at that height (joint5's limit). The bowl's radius is 12 cm.

Things that went wrong while building this (and the fixes)

Eleven problems and their fixes
Symptom Cause Fix
The grasp missed by 2 cm, and the robot had turned 6° the arm's target jumped in one step, and the jolt turned the robot always move the arm smoothly (MoveIt trajectories do that)
The banana slipped out when lifted default friction 0.5, and the banana was grasped off-centre rubber-like friction 1.0, grasp at the middle of its points
The fingers could not close around the banana convexHull made the curved banana a 7 cm blob convexDecomposition
The banana lay on the bowl's rim 19 cm banana, 16 cm bowl a 1.5× bowl, and release the banana across the robot
YOLO: frisbee instead of banana a flat crescent seen from 5.8 cm above the floor the medium model yolo11m.pt
The banana estimate was 5 cm short seen end-on, its far half hides behind its near half look again from the side; use the middle of its length
The mission hung after closing the gripper the squeezing finger reports a velocity, so the controller never detects the stall wait at most 3 s for the gripper
The mug crept across the floor by itself its convex-hull collider (the mug's mesh has a flat base, so the hull is the culprit, not the model) convexDecomposition for the mug
The robot drove through the mustard bottle on its way to park the bottle had no collider, and Nav2 started right next to it colliders for the mug and the bottle, and drive into the open before Nav2 takes over
MoveIt: Start state out of bounds … joint3 after driving the folded pose (joint3 = 1.85) sagged onto the joint limit (1.8567) fold to joint3 = 1.80 (tutorial 03's start pose and the SRDF)
Now and then the mission hung right at the start, after "amcl/get_state service not available, waiting..." right after a service appears, DDS may not have matched both sides yet, and the first request is lost. BasicNavigator.waitUntilNav2Active() then waits for the answer forever wait_until_nav2_active() in mission.py: the same, with a 2 s timeout per request, and retries

Where to go from here

  • Other objects. locate() works for any of YOLO's 80 classes. Give the object physics like the banana, and pick a grasp rule for its shape.
  • Grasp from the side. A tall object such as the bottle needs a horizontal gripper: change the condition \(\theta_2 + \theta_3 + \theta_5 = \pi\) to \(\pi/2\), and put the wrist \(L_3\) in front of the grasp point instead of above it.
  • Train your own detector. Isaac Sim's Replicator can render thousands of labelled images of the lime_room.
  • The real robot. The ROS side uses the real Lime's topic and frame names, so moving to hardware is mostly a matter of swapping the simulation for the real drivers (the JointStateTopicSystem for the Lime's own ros2_control hardware, the RealSense and LDS drivers). This was not tested on a real Lime.
The launch file: lime_isaac_bringup/launch/lime_full.launch.py
# SPDX-FileCopyrightText: 2026 An (an-robotics)
# SPDX-License-Identifier: Apache-2.0

"""Tutorial 13: everything at once - MoveIt 2 + ros2_control, Nav2, YOLO and RViz.

    ros2 launch lime_isaac_bringup lime_full.launch.py
    ros2 run lime_isaac_bringup mission          # the pick-and-place mission (YOLO + MoveIt + Nav2)

Only ONE robot_state_publisher runs (the one in lime_isaac_moveit/moveit.launch.py, whose URDF also
contains the ros2_control block). /joint_states comes from joint_state_broadcaster.
"""

from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, GroupAction, IncludeLaunchDescription
from launch.conditions import IfCondition
from launch.substitutions import LaunchConfiguration, PathJoinSubstitution
from launch_ros.actions import Node
from launch_ros.substitutions import FindPackageShare


def generate_launch_description():
    pkg = FindPackageShare("lime_isaac_bringup")
    return LaunchDescription(
        [
            DeclareLaunchArgument("rviz", default_value="true"),
            DeclareLaunchArgument("params_file", default_value=PathJoinSubstitution([pkg, "config", "nav2_params.yaml"])),
            # MoveIt 2 + ros2_control (+ robot_state_publisher). In a scoped group: otherwise its rviz:=false
            # would leak out and switch off the RViz below as well.
            GroupAction(
                [
                    IncludeLaunchDescription(
                        PathJoinSubstitution([FindPackageShare("lime_isaac_moveit"), "launch", "moveit.launch.py"]),
                        launch_arguments={"rviz": "false"}.items(),
                    )
                ],
                scoped=True,
            ),
            # Nav2 (map_server, AMCL, planner, controller, ...)
            IncludeLaunchDescription(
                PathJoinSubstitution([FindPackageShare("nav2_bringup"), "launch", "bringup_launch.py"]),
                launch_arguments={
                    "map": PathJoinSubstitution([pkg, "maps", "lime_room.yaml"]),
                    "params_file": LaunchConfiguration("params_file"),
                    "use_sim_time": "true",
                    "autostart": "true",
                }.items(),
            ),
            # YOLO - the medium model: from the low camera the nano model (tutorial 10) calls the banana a "frisbee"
            DeclareLaunchArgument("yolo_model", default_value="yolo11m.pt"),
            IncludeLaunchDescription(
                PathJoinSubstitution([FindPackageShare("lime_yolo"), "launch", "yolo.launch.py"]),
                launch_arguments={"model": LaunchConfiguration("yolo_model")}.items(),
            ),
            Node(
                package="rviz2",
                executable="rviz2",
                arguments=["-d", PathJoinSubstitution([pkg, "rviz", "navigation.rviz"])],
                parameters=[{"use_sim_time": True}],
                condition=IfCondition(LaunchConfiguration("rviz")),
                output="screen",
            ),
        ]
    )
Isaac Sim side: isaac/13_all_together.py
# SPDX-FileCopyrightText: 2026 An (an-robotics)
# SPDX-License-Identifier: Apache-2.0

"""Tutorial 13 - Putting it all together: the complete simulated TurtleBot3 Lime.

    source scripts/isaac_env.sh
    python isaac/13_all_together.py

    # ROS 2 container: MoveIt 2 + ros2_control, Nav2, YOLO, RViz - then the mission
    ./docker/run_ros.sh ros2 launch lime_isaac_bringup lime_full.launch.py
    ./docker/run_ros.sh ros2 run lime_isaac_bringup mission

Everything from tutorials 06-12 in one scene:
    /clock  /cmd_vel  /odom  /tf  /isaac_joint_states  /isaac_joint_commands
    /camera/camera/...  /scan  /imu
New here: the objects are real (rigid bodies, colliders, masses): the gripper can pick up the banana, the bowl
holds it, and the mug and the bottle would be knocked over (common/scene.py: setup_pick_and_place).
"""

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 graphs, lime, sensors
from common.scene import OBJECTS, build_lime_room, setup_pick_and_place
from isaacsim.core.experimental.prims import Articulation, XformPrim
from isaacsim.core.simulation_manager import SimulationManager

graphs.enable_ros2_realtime(simulation_app)

stage = stage_utils.create_new_stage(template="empty")
build_lime_room(stage, object_physics=True)  # real objects: colliders and mass, so they can be picked up
while stage_utils.is_stage_loading():
    simulation_app.update()
robot_path = "/World/turtlebot3_lime"
articulation_root = lime.add_lime(robot_path)
setup_pick_and_place(stage, robot_path)  # a bigger bowl, grippy fingers

graphs.create_clock_graph()  # 06
graphs.create_drive_graph(articulation_root)  # 06  /cmd_vel   <- Nav2
graphs.create_odom_tf_joint_states_graph(articulation_root, joint_states_topic="/isaac_joint_states")  # 07 + 12
graphs.create_joint_command_graph(articulation_root)  # 12  /isaac_joint_commands <- ros2_control <- MoveIt
graphs.create_camera_graph(sensors.add_d435_camera(robot_path))  # 08  camera  -> YOLO
graphs.create_lidar_graph(sensors.add_lds_lidar(robot_path))  # 09  /scan    -> Nav2
graphs.create_imu_graph(sensors.add_imu(robot_path))  # 09  /imu

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

    CLOSE_UP = ((1.75, -1.05, 0.85), (0.85, 0.12, 0.05))  # pick and place
    OVERVIEW = ((0.9, -4.4, 3.6), (1.0, -0.4, 0.0))  # parking
    recorder = Recorder(args.record, eye=CLOSE_UP[0], target=CLOSE_UP[1], every_n=8, fps=24)

SimulationManager.setup_simulation(dt=1.0 / 60.0)
app_utils.play()
simulation_app.update()
robot = Articulation(articulation_root)
arm = robot.get_dof_indices(lime.ARM_JOINTS)
print("[13] ready: ros2 launch lime_isaac_bringup lime_full.launch.py, then ros2 run lime_isaac_bringup mission", flush=True)

# --test: follow the mission from the simulation's point of view (ground truth)
banana = XformPrim("/World/LimeRoom/Objects/Banana")
others = {name: XformPrim(f"/World/LimeRoom/Objects/{name}") for name in ("Mug", "Bottle")}  # must not be touched
start = {}  # where they rest after settling (recorded 1 s into the simulation)
BOWL = np.array(next(o for o in OBJECTS if o[0] == "Bowl")[2:4])
CORNER = np.array([2.8, -1.8])
events, steps, still_since, view_blend, still_frame = {}, 0, None, 0.0, -1
if args.test or args.record:
    print(f"[13] ground truth: banana at {np.round(banana.get_world_poses()[0].numpy()[0, :2], 3)}, bowl at {BOWL}", flush=True)


def event(name, text):
    events[name] = steps / 60
    print(f"[13] {text} at t = {events[name]:.0f} s", flush=True)


while simulation_app.is_running():
    simulation_app.update()
    steps += 1
    if recorder:
        if "folded" in events and view_blend < 1.0:  # glide from the close-up to the overview for the parking
            view_blend = min(1.0, view_blend + 1 / 180)
            a = 0.5 - 0.5 * np.cos(np.pi * view_blend)
            recorder.look_at(*[(1 - a) * np.array(c) + a * np.array(o) for c, o in zip(CLOSE_UP, OVERVIEW)])
        recorder.capture()
    if args.test or args.record:
        if steps == 60:
            start = {name: prim.get_world_poses()[0].numpy()[0].copy() for name, prim in others.items()}
        xy = robot.get_world_poses()[0].numpy()[0, :2]
        q = robot.get_dof_positions(dof_indices=arm).numpy()[0]
        for name, prim in others.items():  # report the moment the robot bumps into the mug or the bottle
            if start and f"bumped {name}" not in events and np.linalg.norm(prim.get_world_poses()[0].numpy()[0] - start[name]) > 0.005:
                event(f"bumped {name}", f"{name.lower()} bumped (robot at {np.round(xy, 2)})")
        b = banana.get_world_poses()[0].numpy()[0]
        if "lifted" not in events and b[2] > 0.10:
            event("lifted", f"banana lifted ({b[2] * 100:.0f} cm above the floor)")
        in_bowl = np.linalg.norm(b[:2] - BOWL) < 0.07 and b[2] < 0.10
        still_since = (still_since or steps) if in_bowl else None
        if "lifted" in events and "in_bowl" not in events and still_since and steps - still_since > 60:
            event("in_bowl", f"banana in the bowl, {np.linalg.norm(b[:2] - BOWL) * 100:.1f} cm from its centre")
        if "in_bowl" in events and "folded" not in events and np.max(np.abs(q - np.array(lime.ARM_HOME))) < 0.05:
            event("folded", "arm folded")
            still_frame = len(recorder.frames) - 1 if recorder else -1  # the picture for the docs: banana in the bowl
        if "folded" in events and "parked" not in events and np.linalg.norm(xy - CORNER) < 0.3:
            event("parked", "robot parked in the far corner")
        if ("parked" in events and steps / 60 > events["parked"] + 5) or steps > 500 * 60:
            break  # (5 s more, so the mission can finish cleanly)

ok = True
if args.test:
    b = banana.get_world_poses()[0].numpy()[0]
    checks = {
        "banana picked up (more than 10 cm above the floor)": "lifted" in events,
        "banana put into the bowl (within 7 cm of its centre)": "in_bowl" in events,
        "arm folded afterwards": "folded" in events,
        "robot parked in the far corner (within 0.3 m)": "parked" in events,
        f"banana still in the bowl at the end ({np.linalg.norm(b[:2] - BOWL) * 100:.1f} cm from its centre)": np.linalg.norm(b[:2] - BOWL) < 0.07,
    }
    for name, prim in others.items():
        moved = np.linalg.norm(prim.get_world_poses()[0].numpy()[0] - start[name])
        checks[f"{name.lower()} not bumped into (moved {moved * 100:.1f} cm)"] = moved < 0.01
    for text, passed in checks.items():
        print(f"[13][check] {'ok  ' if passed else 'FAIL'} {text}")
    ok = all(checks.values())
    print(f"[13][test] {'PASS' if ok else 'FAIL'}")
if recorder:
    recorder.save(still_index=still_frame)
app_utils.stop()
simulation_app.close(exit_code=0 if ok else 1)
sys.exit(0 if ok else 1)
The whole mission: lime_isaac_bringup/scripts/mission.py
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2026 An (an-robotics)
# SPDX-License-Identifier: Apache-2.0

"""Tutorial 13 mission: tidy up the lime_room - put the banana into the bowl, then park.

    ros2 run lime_isaac_bringup mission

  1. YOLO + depth   find the banana: a 2D box + the depth image + TF -> a 3D position and direction
  2. drive          drive up to it, centimetre-accurate, with odometry
  3. MoveIt         pick it up: top-down grasp, fingers across the banana
  4. YOLO + depth   find the bowl, drive up to it
  5. MoveIt         put the banana into the bowl, fold the arm
  6. Nav2           park in the far corner of the room
"""

import math
import sys
import threading
import time

import numpy as np
import rclpy
import tf2_ros
from control_msgs.action import GripperCommand
from geometry_msgs.msg import Pose, PoseStamped, Twist
from moveit_msgs.action import MoveGroup
from moveit_msgs.msg import CollisionObject, Constraints, JointConstraint, MoveItErrorCodes, PlanningScene
from moveit_msgs.srv import ApplyPlanningScene
from nav2_simple_commander.robot_navigator import BasicNavigator, TaskResult
from rclpy.action import ActionClient
from rclpy.executors import SingleThreadedExecutor
from rclpy.parameter import Parameter
from sensor_msgs.msg import CameraInfo, Image
from shape_msgs.msg import SolidPrimitive
from vision_msgs.msg import Detection2DArray

ARM_JOINTS = [f"joint{i}" for i in range(1, 7)]
HOME = [0.0, -1.10, 1.80, 0.0, 0.98, 0.0]  # folded (the SRDF "home" pose)
CARRY = [0.0, -0.3, 1.2, 0.0, 1.0, 0.0]  # banana held high above the robot, out of the camera's view
GRIPPER_OPEN, GRIPPER_CLOSED = 0.019, -0.010
CAMERA = "/camera/camera"
PARK = (2.8, -1.8, 0.0)


def wrap(a):
    return (a + math.pi) % (2 * math.pi) - math.pi


# The arm in the base_footprint frame (from the URDF): joint1 turns about a vertical axis at x = -0.024;
# joint2, joint3 and joint5 tilt the arm forward; joint4 and joint6 roll. Looking straight down, the arm is
# a planar 2-link arm (upper arm L1, forearm L2) plus L3 from the wrist to end_effector_link (the fingertips
# reach 2 cm further down).
SHOULDER_X, SHOULDER_Z = -0.024, 0.2065
L1, L2, L3 = 0.124, 0.1045, 0.1625


def top_down_ik(x, y, z, object_yaw):
    """Joint angles that put end_effector_link at (x, y, z) [base_footprint frame], pointing straight down,
    with the fingers closing across an object whose long axis points along object_yaw. None = out of reach."""
    j1 = math.atan2(y, x - SHOULDER_X)
    r = math.hypot(x - SHOULDER_X, y)  # horizontal distance from joint1's axis
    dz = z + L3 - SHOULDER_Z  # the wrist is L3 above end_effector_link
    c3 = (r * r + dz * dz - L1 * L1 - L2 * L2) / (2 * L1 * L2)  # law of cosines
    if abs(c3) > 1.0:
        return None
    j3 = math.acos(c3)  # elbow up
    j2 = math.atan2(r, dz) - math.atan2(L2 * math.sin(j3), L1 + L2 * math.cos(j3))
    j5 = math.pi - j2 - j3  # the three tilts add up to 180 deg: pointing down
    j6 = (j1 - object_yaw + math.pi / 2) % math.pi - math.pi / 2  # fingers across the object (either way round)
    joints = [j1, j2, j3, 0.0, j5, j6]
    limits = [(-2.82, 2.82), (-1.69, 1.76), (-1.75, 1.85), (-1.57, 1.57), (-1.66, 1.78), (-2.82, 2.82)]
    return joints if all(lo <= j <= hi for j, (lo, hi) in zip(joints, limits)) else None


class Lime:
    """Everything the mission needs: perception, the base, the arm. Nav2 is the BasicNavigator node."""

    def __init__(self):
        self.nav = BasicNavigator("lime_mission")
        self.nav.set_parameters([Parameter("use_sim_time", Parameter.Type.BOOL, True)])
        self.log = self.nav.get_logger()
        # TF on its own node + thread, so lookups work while the main node waits for actions
        self.tf_node = rclpy.create_node("lime_mission_tf", parameter_overrides=[Parameter("use_sim_time", Parameter.Type.BOOL, True)])
        self.tf = tf2_ros.Buffer()
        tf2_ros.TransformListener(self.tf, self.tf_node)
        self.executor = SingleThreadedExecutor()
        self.executor.add_node(self.tf_node)
        self.tf_thread = threading.Thread(target=self.executor.spin, daemon=True)
        self.tf_thread.start()

        n = self.nav
        self.detections, self.depth, self.K = [], {}, None
        n.create_subscription(Detection2DArray, "/detections", self.on_detections, 10)
        n.create_subscription(Image, f"{CAMERA}/aligned_depth_to_color/image_raw", self.on_depth, 5)
        n.create_subscription(CameraInfo, f"{CAMERA}/color/camera_info", lambda m: setattr(self, "K", np.array(m.k).reshape(3, 3)), 1)
        self.cmd = n.create_publisher(Twist, "/cmd_vel", 10)
        self.arm = ActionClient(n, MoveGroup, "/move_action")
        self.grip = ActionClient(n, GripperCommand, "/gripper_controller/gripper_cmd")
        self.scene = n.create_client(ApplyPlanningScene, "/apply_planning_scene")

    def close(self):
        """Stop the TF thread and the nodes before exiting (otherwise Python aborts at exit)."""
        self.send(0.0, 0.0)
        self.executor.shutdown()
        self.tf_thread.join(timeout=2.0)
        self.tf_node.destroy_node()
        self.nav.destroy_node()
        rclpy.try_shutdown()

    def on_depth(self, msg):
        self.depth[(msg.header.stamp.sec, msg.header.stamp.nanosec)] = msg
        while len(self.depth) > 60:
            self.depth.pop(next(iter(self.depth)))

    def on_detections(self, msg):
        """Keep each detection together with the depth image taken at the same moment (same time stamp)."""
        depth = self.depth.get((msg.header.stamp.sec, msg.header.stamp.nanosec))
        if depth is not None:
            self.detections.append((msg, depth))
            del self.detections[:-60]  # the last 60 only (each holds a depth image)

    def spin_for(self, seconds):
        end = time.time() + seconds
        while time.time() < end:
            rclpy.spin_once(self.nav, timeout_sec=0.05)

    def wait(self, future):
        rclpy.spin_until_future_complete(self.nav, future)
        return future.result()

    def locate(self, name, seconds=4.0):
        """Find object `name` with YOLO and measure where it is: a 3D point cloud of the object, in the odom frame.

        2D box (YOLO)  +  depth image  +  camera model  ->  3D points in the camera frame
                       +  TF odom <- camera at the image's time stamp  ->  3D points in the odom frame
        """
        self.detections.clear()
        self.spin_for(seconds)  # collect a few seconds of detections, keep the most confident one
        best = None
        for msg, depth_msg in self.detections:
            for d in msg.detections:
                h = d.results[0].hypothesis
                if h.class_id == name and (best is None or h.score > best[0]):
                    best = (h.score, d, msg.header, depth_msg)
        if best is None or self.K is None:
            return None
        score, det, header, depth_msg = best
        pts, camera = self.points(det, header, depth_msg)
        return None if pts is None else {"score": score, "points": pts, "camera": camera}

    def points(self, det, header, depth_msg):
        """The 3D points (odom frame) of one detection's box, and where the camera was. (None, None) if too few."""
        depth = np.frombuffer(depth_msg.data, dtype=np.float32).reshape(depth_msg.height, depth_msg.width)
        cx, cy = det.bbox.center.position.x, det.bbox.center.position.y
        w, h = det.bbox.size_x, det.bbox.size_y
        u0, u1 = int(max(cx - w / 2, 0)), int(min(cx + w / 2, depth_msg.width - 1))
        v0, v1 = int(max(cy - h / 2, 0)), int(min(cy + h / 2, depth_msg.height - 1))
        v, u = np.mgrid[v0:v1 + 1, u0:u1 + 1]
        z = depth[v0:v1 + 1, u0:u1 + 1]
        ok = np.isfinite(z) & (z > 0.05) & (z < 3.0)
        fx, fy, px, py = self.K[0, 0], self.K[1, 1], self.K[0, 2], self.K[1, 2]
        cam = np.stack([(u[ok] - px) * z[ok] / fx, (v[ok] - py) * z[ok] / fy, z[ok]], axis=1)  # optical frame
        tf = self.tf.lookup_transform("odom", header.frame_id, header.stamp, timeout=rclpy.duration.Duration(seconds=1.0))
        t, q = tf.transform.translation, tf.transform.rotation
        R = quat_to_matrix(q.x, q.y, q.z, q.w)
        pts = cam @ R.T + np.array([t.x, t.y, t.z])
        pts = pts[(pts[:, 2] > 0.006) & (pts[:, 2] < 0.40)]  # drop the floor (z = 0) around the object
        if len(pts) < 20:
            return None, None
        middle = np.median(pts[:, :2], axis=0)
        pts = pts[np.linalg.norm(pts[:, :2] - middle, axis=1) < 0.25]  # drop the background inside the box
        return pts, np.array([t.x, t.y])

    def pose(self):
        """Robot pose (x, y, yaw) in the odom frame - Isaac Sim's odometry, through TF."""
        tf = self.tf.lookup_transform("odom", "base_footprint", rclpy.time.Time(), timeout=rclpy.duration.Duration(seconds=1.0))
        t, q = tf.transform.translation, tf.transform.rotation
        return t.x, t.y, math.atan2(2 * (q.w * q.z + q.x * q.y), 1 - 2 * (q.y * q.y + q.z * q.z))

    def send(self, v, w):
        msg = Twist()
        msg.linear.x, msg.angular.z = float(v), float(w)
        self.cmd.publish(msg)

    def turn_to(self, yaw):
        w, end = 0.0, time.time() + 30.0
        while time.time() < end:
            error = wrap(yaw - self.pose()[2])
            if abs(error) < 0.01:
                break
            target = math.copysign(min(0.5, max(0.08, 1.5 * abs(error))), error)
            w += max(-0.03, min(0.03, target - w))  # gentle acceleration: the robot carries things
            self.send(0.0, w)
            time.sleep(0.05)
        self.send(0.0, 0.0)
        time.sleep(0.5)

    def drive_to(self, x, y, backwards=False):
        """Turn towards (x, y) [odom frame], drive there in a straight line, stop within a centimetre."""
        px, py, _ = self.pose()
        heading = math.atan2(y - py, x - px) + (math.pi if backwards else 0.0)
        self.turn_to(heading)
        v, sign, end = 0.0, -1.0 if backwards else 1.0, time.time() + 60.0
        while time.time() < end:
            px, py, yaw = self.pose()
            ahead = (x - px) * math.cos(yaw) + (y - py) * math.sin(yaw)  # distance left along the heading
            if sign * ahead < 0.008:
                break
            target = min(0.12, max(0.02, 0.8 * abs(ahead)))
            v += max(-0.01, min(0.01, target - v))
            side = -(x - px) * math.sin(yaw) + (y - py) * math.cos(yaw)
            self.send(sign * v, max(-0.3, min(0.3, 2.0 * side * sign)) if abs(ahead) > 0.05 else 0.0)
            time.sleep(0.05)
        self.send(0.0, 0.0)
        time.sleep(0.5)

    def to_base(self, x, y):
        """odom-frame point -> base_footprint frame (where the arm works)."""
        px, py, yaw = self.pose()
        dx, dy = x - px, y - py
        return dx * math.cos(yaw) + dy * math.sin(yaw), -dx * math.sin(yaw) + dy * math.cos(yaw)

    # --- the arm (MoveIt 2) and the gripper (ros2_control) ---
    def move_arm(self, joints, what):
        goal = MoveGroup.Goal()
        goal.request.group_name = "arm"
        goal.request.num_planning_attempts = 5
        goal.request.allowed_planning_time = 5.0
        goal.request.max_velocity_scaling_factor = 0.3
        goal.request.max_acceleration_scaling_factor = 0.3
        goal.request.goal_constraints = [
            Constraints(
                joint_constraints=[
                    JointConstraint(joint_name=n, position=p, tolerance_above=0.01, tolerance_below=0.01, weight=1.0)
                    for n, p in zip(ARM_JOINTS, joints)
                ]
            )
        ]
        handle = self.wait(self.arm.send_goal_async(goal))
        ok = handle.accepted and self.wait(handle.get_result_async()).result.error_code.val == MoveItErrorCodes.SUCCESS
        self.log.info(f"MoveIt: {what}: {'done' if ok else 'FAILED'}")
        return ok

    def gripper(self, position, seconds=3.0):
        """Open / close the gripper. Closing on the banana, the fingers stop at the banana. The controller would
        call that a "stall" once the finger velocity is ~0, but in simulation the squeezing finger reports a
        velocity (about 0.3 m/s) although it does not move, so the goal never finishes. Wait at most `seconds`:
        the goal stays active, and the controller keeps commanding the closed position, so the fingers keep
        squeezing."""
        goal = GripperCommand.Goal()
        goal.command.position, goal.command.max_effort = position, 10.0
        handle = self.wait(self.grip.send_goal_async(goal))
        result = handle.get_result_async()
        rclpy.spin_until_future_complete(self.nav, result, timeout_sec=seconds)
        return handle.accepted

    def add_floor(self):
        """Tell MoveIt about the floor, so no planned arm motion goes through it."""
        floor = CollisionObject(id="floor", operation=CollisionObject.ADD)
        floor.header.frame_id = "base_footprint"
        floor.primitives = [SolidPrimitive(type=SolidPrimitive.BOX, dimensions=[3.0, 3.0, 0.02])]
        floor.primitive_poses = [Pose()]
        floor.primitive_poses[0].position.z = -0.02  # top at -1 cm: below the wheels, above nothing else
        floor.primitive_poses[0].orientation.w = 1.0
        request = ApplyPlanningScene.Request(scene=PlanningScene(is_diff=True))
        request.scene.world.collision_objects = [floor]
        self.scene.wait_for_service(timeout_sec=30.0)
        return self.wait(self.scene.call_async(request)).success


def wait_until_nav2_active(nav):
    """BasicNavigator.waitUntilNav2Active(), but with a timeout on every service call, and retries.

    Right after a service appears, DDS may not have finished matching both sides, and the first request can get
    lost. The original then waits for its answer forever (it happened twice in about 25 runs)."""
    from lifecycle_msgs.srv import GetState

    for node in ("amcl", "bt_navigator"):
        client = nav.create_client(GetState, f"{node}/get_state")
        while True:
            if not client.wait_for_service(timeout_sec=1.0):
                nav.info(f"{node}/get_state service not available, waiting...")
                continue
            future = client.call_async(GetState.Request())
            rclpy.spin_until_future_complete(nav, future, timeout_sec=2.0)
            if future.done() and future.result() is not None and future.result().current_state.label == "active":
                break
            time.sleep(1.0)  # not active yet, or the answer got lost: ask again
        nav.destroy_client(client)
        if node == "amcl":
            nav._waitForInitialPose()  # BasicNavigator's own: (re)publish the initial pose until AMCL has it
    nav.info("Nav2 is ready for use!")


def quat_to_matrix(x, y, z, w):
    return np.array(
        [
            [1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
            [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
            [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)],
        ]
    )


def long_object(found):
    """A lying object (the banana): its direction = the main axis of its points (PCA); the grasp point = the
    middle of its length. Not simply the average point: the end nearer the camera gets more depth pixels."""
    xy = found["points"][:, :2]
    mean = xy.mean(axis=0)
    eigenvalues, eigenvectors = np.linalg.eigh(np.cov((xy - mean).T))
    axis = eigenvectors[:, np.argmax(eigenvalues)]
    normal = np.array([-axis[1], axis[0]])
    along, across = (xy - mean) @ axis, (xy - mean) @ normal
    middle = (np.percentile(along, 2) + np.percentile(along, 98)) / 2  # halfway between the two ends
    at_middle = np.abs(along - middle) < 0.02  # the slice of the object there (a banana is curved)
    centre = mean + middle * axis + np.median(across[at_middle]) * normal
    return centre, math.atan2(axis[1], axis[0])


def round_object(found):
    """A round object (the bowl): the camera sees only its front, so centre = front surface + one radius
    further along the line of sight; the radius is half the width the camera sees."""
    xy = found["points"][:, :2]
    ray = np.median(xy, axis=0) - found["camera"]
    ray /= np.linalg.norm(ray)
    side = np.array([-ray[1], ray[0]])
    along, across = (xy - found["camera"]) @ ray, (xy - found["camera"]) @ side
    radius = (np.percentile(across, 98) - np.percentile(across, 2)) / 2
    front = np.percentile(along, 5)
    middle = (np.percentile(across, 98) + np.percentile(across, 2)) / 2
    return found["camera"] + (front + radius) * ray + middle * side, radius


def main():
    rclpy.init()
    lime = Lime()
    log = lime.log

    def fail(text):
        log.error(text)
        lime.close()
        sys.exit(1)

    p = PoseStamped()
    p.header.frame_id = "map"
    p.header.stamp = lime.nav.get_clock().now().to_msg()
    p.pose.orientation.w = 1.0
    lime.nav.setInitialPose(p)  # the robot starts at the map origin
    wait_until_nav2_active(lime.nav)
    if not (lime.arm.wait_for_server(timeout_sec=60.0) and lime.grip.wait_for_server(timeout_sec=60.0)):
        fail("MoveIt / gripper action servers not available")
    lime.add_floor()
    lime.spin_for(1.0)

    # 1. Find the banana and the bowl from where we are (the banana is small and far: collect a few seconds).
    found, found_bowl = lime.locate("banana", seconds=6.0), lime.locate("bowl", seconds=2.0)
    if found is None or found_bowl is None:
        fail("YOLO: I need to see both the banana and the bowl")
    banana, _ = long_object(found)
    bowl, _ = round_object(found_bowl)
    log.info(f"YOLO: banana ({found['score']:.2f}) at ({banana[0]:.2f}, {banana[1]:.2f}), bowl ({found_bowl['score']:.2f}) at ({bowl[0]:.2f}, {bowl[1]:.2f})")

    # 2. From here we see the banana almost end-on: its far half hides behind its near half. Look again from
    #    45 cm away and 55 deg further round (the side away from the mug): now the whole banana is visible.
    x, y, _ = lime.pose()
    look = math.atan2(banana[1] - y, banana[0] - x) + math.radians(55)
    toward = np.array([math.cos(look), math.sin(look)])
    lime.drive_to(*(banana - 0.45 * toward))
    lime.turn_to(look)
    found = lime.locate("banana")
    if found is None:
        fail("YOLO: lost the banana")
    banana, banana_yaw = long_object(found)
    log.info(f"YOLO: banana ({found['score']:.2f}) at ({banana[0]:.3f}, {banana[1]:.3f}), pointing {math.degrees(banana_yaw) % 180:.0f} deg")

    # 3. Stop with the banana 16 cm in front of the robot: inside the arm's reach for a top-down grasp.
    lime.drive_to(*(banana - 0.16 * toward))
    lime.turn_to(look)

    # 4. Pick it up.
    lime.gripper(GRIPPER_OPEN)
    bx, by = lime.to_base(*banana)
    yaw = wrap(banana_yaw - lime.pose()[2])  # the banana's direction as seen from the robot
    above, grasp, lifted = (top_down_ik(bx, by, z, yaw) for z in (0.10, 0.03, 0.15))
    if None in (above, grasp, lifted):
        fail(f"the banana at ({bx:.3f}, {by:.3f}) in the robot frame is out of reach")
    if not (lime.move_arm(above, "above the banana") and lime.move_arm(grasp, "down to the banana")):
        fail("MoveIt: grasp failed")
    lime.gripper(GRIPPER_CLOSED)  # stops when the fingers touch the banana, and keeps squeezing
    if not (lime.move_arm(lifted, "lift") and lime.move_arm(CARRY, "carry")):
        fail("MoveIt: lift failed")

    # 5. Back to the bowl. The mug stands between the banana and the bowl, so go round: approach the bowl
    #    from its open side (from -y, 42 cm away), look again, and drive up until the bowl is 20 cm in front.
    lime.drive_to(bowl[0], bowl[1] - 0.42)
    lime.turn_to(math.pi / 2)
    found = lime.locate("bowl")
    if found is None:
        fail("YOLO: lost the bowl")
    bowl, radius = round_object(found)
    log.info(f"YOLO: bowl ({found['score']:.2f}) at ({bowl[0]:.3f}, {bowl[1]:.3f}), radius {radius * 100:.0f} cm")
    lime.drive_to(bowl[0], bowl[1] - 0.20)
    lime.turn_to(math.pi / 2)

    # 6. Put the banana in: above the bowl's centre, or as close to it as the arm reaches; banana across the robot.
    bx, by = lime.to_base(*bowl)
    release = next((q for x in np.arange(bx, 0.10, -0.005) if (q := top_down_ik(x, by, 0.13, math.pi / 2))), None)
    if release is None or not lime.move_arm(release, "above the bowl"):
        fail("MoveIt: could not reach the bowl")
    lime.gripper(GRIPPER_OPEN)
    lime.spin_for(1.0)
    lime.move_arm(HOME, "arm folded")

    # 7. Back away from the bowl and drive into the open middle of the room, then let Nav2 park the robot.
    #    (Started right next to the bottle, Nav2 would steer the robot straight through it.)
    x, y, yaw = lime.pose()
    lime.drive_to(x - 0.12 * math.cos(yaw), y - 0.12 * math.sin(yaw), backwards=True)
    lime.drive_to(bowl[0] + 0.6, bowl[1] - 0.45)
    log.info(f"Nav2: parking at ({PARK[0]}, {PARK[1]})")
    goal = PoseStamped()
    goal.header.frame_id = "map"
    goal.pose.position.x, goal.pose.position.y = PARK[0], PARK[1]
    goal.pose.orientation.w = 1.0
    lime.nav.goToPose(goal)
    while not lime.nav.isTaskComplete():
        time.sleep(0.2)
    if lime.nav.getResult() != TaskResult.SUCCEEDED:
        fail(f"Nav2: could not park: {lime.nav.getResult()}")
    log.info("mission complete: the banana is in the bowl")
    lime.close()


if __name__ == "__main__":
    main()

Next: 14 · Make your own map with SLAM. Tutorial 16 builds on this one: three bananas the robot has to find first, all run by a behavior tree.