diff --git a/_data/navigation.yml b/_data/navigation.yml index d979757f..e1b0b209 100644 --- a/_data/navigation.yml +++ b/_data/navigation.yml @@ -197,6 +197,8 @@ wiki: url: /wiki/actuation/led-lights/ - title: Selecting the Right Motor for Your Application url: /wiki/actuation/selecting-the-right-motor/ + - title: Visual Servoing for Perpendicular Contact with a Multi-DOF Robotic Arm + url: /wiki/actuation/visual-servoing-perpendicular-contact/ - title: Machine Learning url: /wiki/machine-learning/ children: diff --git a/assets/images/visual-servoing-contact-approach.png b/assets/images/visual-servoing-contact-approach.png new file mode 100644 index 00000000..55df57d2 Binary files /dev/null and b/assets/images/visual-servoing-contact-approach.png differ diff --git a/assets/images/visual-servoing-contact-pipeline.png b/assets/images/visual-servoing-contact-pipeline.png new file mode 100644 index 00000000..5541a3f9 Binary files /dev/null and b/assets/images/visual-servoing-contact-pipeline.png differ diff --git a/wiki/actuation/index.md b/wiki/actuation/index.md index 9d121c1f..e4e0976b 100644 --- a/wiki/actuation/index.md +++ b/wiki/actuation/index.md @@ -48,6 +48,9 @@ The "Controls & Actuation" section provides a detailed guide to implementing and - **[Vedder Open-Source Electronic Speed Controller](/wiki/actuation/vedder-electronic-speed-controller/)** Highlights features and advantages of the Vedder ESC, an open-source electronic speed controller for brushless DC motors. +- **[Visual Servoing for Perpendicular Contact with a Multi-DOF Robotic Arm](/wiki/actuation/visual-servoing-perpendicular-contact/)** + Tutorial on making a low-cost arm press a tool flat against a wall it sees with an RGB-D camera: contact-pose IK, joint calibration by touching a tag board, fusing AprilTags with depth, wall-safe approach planning, and a contact state machine. + ## Resources - [Drive-by-wire System Overview](https://carbiketech.com/drive-by-wire-technology-working/) @@ -60,3 +63,4 @@ The "Controls & Actuation" section provides a detailed guide to implementing and - [Pure-Pursuit Algorithm Reference](https://www.ri.cmu.edu/pub_files/pub3/coulter_r_craig_1992_1/coulter_r_craig_1992_1.pdf) - [ULN 2003A Documentation](https://www.ti.com/lit/ds/symlink/uln2003a.pdf) - [Vedder ESC Project](http://vedder.se/2015/01/vesc-open-source-esc/) +- [ViSP: Visual Servoing Platform](https://visp.inria.fr/) diff --git a/wiki/actuation/visual-servoing-perpendicular-contact.md b/wiki/actuation/visual-servoing-perpendicular-contact.md new file mode 100644 index 00000000..151f61a2 --- /dev/null +++ b/wiki/actuation/visual-servoing-perpendicular-contact.md @@ -0,0 +1,374 @@ +--- +# Jekyll 'Front Matter' goes here. Most are set by default, and should NOT be +# overwritten except in special circumstances. +# You should set the date the article was last updated like this: +date: 2026-11-30 # YYYY-MM-DD +# This will be displayed at the bottom of the article +# You should set the article's title: +title: Visual Servoing for Perpendicular Contact with a Multi-DOF Robotic Arm +# The 'title' is automatically displayed at the top of the page +# and used in other parts of the site. +--- +This tutorial explains how to make a low-cost, servo-driven robotic arm press a flat tool face squarely against a point on a wall that it sees with an RGB-D camera, and hold it there while the wall or the arm's own base moves. It follows a position-based visual servoing pipeline in the order you would build it: giving the arm enough degrees of freedom to face the wall, solving inverse kinematics for a position plus an approach direction, calibrating the camera and the arm together by touching a printed board, fusing fiducial markers with depth to estimate the wall, planning a collision-free approach, and closing the loop with a contact state machine. + +The examples come from a CMU MRSD project in which an SO-101 arm, driven through Hugging Face LeRobot, hangs under a hovering drone and touches points on a vertical wall. The arm's gripper was replaced by a sixth joint and a straight rod, an Intel RealSense D435 is mounted rigidly next to the arm's base, and the wall carries a printed AprilTag board. Because the drone drifts by centimeters even while it hovers, the arm cannot simply move to a precomputed pose; it has to measure the wall in every camera frame and correct its motion. The same pipeline applies to a fixed arm working on a moving part, or to any arm with a URDF model and joint-position control. Each step lists the checks that catch its errors before they reach the next step, because in a chain like this a 5° joint zero error shows up much later as a contact that is consistently 2 cm off. Numerical values given below are starting points and rules of thumb, not requirements; tune them for your own hardware. + +This entry builds on several existing pages: [Visual Servoing](/wiki/state-estimation/visual-servoing/) derives image-based servoing for a drone, the [Hand-Eye Calibration](/wiki/sensing/handeye-calibration/) entries solve the AX = XB problem with markers, and [Task Prioritization Control](/wiki/actuation/task-prioritization-control/) introduces the null-space projection used for the inverse kinematics in Step 2. + +## Background and System Overview + +### Flush contact is a five-dimensional task +Many contact tasks, such as pressing a button, placing a sensor probe, wiping, drilling, or nondestructive inspection, need more than tip position. A flat tool face only touches flush if its axis is aligned with the surface normal. Writing the contact goal as a point $$\mathbf{p}$$ on the surface and the outward unit normal $$\mathbf{n}$$, the tool must satisfy: + +- **Position (3 constraints):** the center of the tool face is at $$\mathbf{p} + d\,\mathbf{n}$$, where $$d$$ is a small contact offset (a few millimeters to hover just off the surface; 0 to touch it). +- **Approach direction (2 constraints):** the tool axis $$\mathbf{z}$$ points along $$-\mathbf{n}$$. +- **Roll about the tool axis (free):** a round rod looks the same at any roll angle. + +That makes five task dimensions. A 5-DOF arm has exactly enough joints in principle, but only if they are arranged so that they can actually produce every approach direction. Step 1 shows that the joints of the stock SO-101 are not. + +### Why position-based visual servoing +Visual servoing closes the control loop through a camera: after each motion, the camera measures what is left of the error and the next command is computed from it [3], [6]. Image-based visual servoing (IBVS) drives image-feature errors to zero directly. Position-based visual servoing (PBVS) first reconstructs the target's 3D pose and then controls the robot toward it. For contact with an RGB-D camera, PBVS is the natural choice: the contact offset and the surface normal are metric quantities, the depth image measures the wall plane directly, and the planner needs a 3D target to check the arm against the wall. The cost is that accuracy depends on calibration, which is why Step 3 is the longest step. + +The camera in the example is mounted rigidly to the same frame as the arm's base. One fixed transform therefore relates the camera to the base, even though the whole assembly moves with the drone. What the loop has to track is the wall's motion relative to the base, and the camera measures exactly that. + +### Pipeline +Figure 1 shows the complete system. Steps 1 to 3 are done once and repeated only when the hardware changes. Steps 4 to 6 run on every camera frame. Table 1 lists the components of the example system and common alternatives. + +![Pipeline: offline setup (Steps 1 to 3) feeds a calibrated chain and camera-to-base transform into the online loop (Steps 4 to 6)](/assets/images/visual-servoing-contact-pipeline.png) +*Figure 1. Offline setup (Steps 1 to 3) and the online visual servoing loop (Steps 4 to 6).* + +**Table 1.** Components of the example system and common alternatives. + +| Component | Example system | Alternatives | +|---|---|---| +| Arm | SO-101 follower, Feetech STS3215 serial-bus servos; gripper replaced by a sixth joint and a straight rod | Any arm with joint-position control and a URDF | +| Driver | LeRobot Python API (reads joints, sends goals, writes PID registers) | Vendor SDK, `ros2_control` | +| Camera | Intel RealSense D435: color 1280x720 and depth 848x480 at 30 fps, depth aligned to color | RealSense D405 (short range), Orbbec Gemini, Stereolabs ZED | +| Target | Printed board of tag36h11 AprilTags on the wall, larger than the camera's view | ArUco or STag board, learned detector plus depth plane | +| Libraries | NumPy, OpenCV (`cv2.aruco` AprilTag detector, `solvePnP`), `pyrealsense2` | Pinocchio or KDL (kinematics), Open3D (point clouds) | +| Compute | Laptop for development; NVIDIA Jetson on the drone | Any computer with USB 3 for the camera | + +## Step 1: Give the Arm a Wrist That Can Face the Wall +For the SO-100/SO-101 family, follow the Seeed Studio guide [12] and the LeRobot documentation [5] to print, assemble, configure the servo IDs, and calibrate the arm, and check that teleoperation with the leader arm works before adding any perception. This step covers what those guides do not: whether the arm can face a surface at all, and what to change if it cannot. + +### Check the reachable approach directions first +The stock SO-101 has a pan joint, three pitch joints (shoulder lift, elbow flex, wrist flex), and a wrist roll. All pitch axes are parallel, so the tool axis always lies in the vertical plane through the pan axis and the tool tip. The arm can face a wall it sees head-on, but not a wall that is turned sideways. A quick way to find this before building anything is to run your IK (Step 2) on contact poses with tilted surfaces and look at the remaining angle between the tool axis and the normal. Table 2 shows the result for a contact point about 30 cm in front of the base. + +**Table 2.** Remaining angle between the tool axis and the surface normal for walls tilted in different directions. + +| Wall tilt (yaw / pitch) | Stock 5-DOF arm | 6-DOF rod arm | +|---|---|---| +| 0° / 0° | 0.1° | 0.0° | +| ±30° / 0° | 28° | 0.0° | +| 45° / 0° | 43° | 0.0° | +| 25° / −25° | 28° | 16° (wrist flex at its limit) | + +The stock arm misses a sideways-tilted wall by almost the full tilt angle. A sixth joint fixes this everywhere except where another joint runs into its limit. + +### Add a sixth joint +The fix in the example was to turn the gripper servo into an active joint. The gripper jaws were removed, the servo (called A below) was mounted on the output of the wrist-roll servo (B), and a straight rod was attached to A's horn. The geometry was chosen so that the kinematics stay simple: + +- A's axis is perpendicular to B's axis and intersects it, a distance D beyond the wrist-flex axis. +- At A = 0 the rod is collinear with B's axis. The rod face is a distance L from A's axis. +- The tool frame sits at the center of the rod face with +Z pointing out of the rod, so at contact +Z equals $$-\mathbf{n}$$. + +Six joints for a five-dimensional task leave one redundant degree of freedom, which the IK uses in Step 2. D and L do not have to be measured precisely; Step 3 estimates corrections to both. + +### Update the model and the servo zeros +1. **Copy the URDF; do not edit the original.** Old scripts that still drive servo 6 as a 0 to 100 gripper will swing the new joint around. In the copy, remove the jaw links and the gripper joint, add a revolute joint for A with its limits, and add a rod link and a fixed tool frame. The masses only matter in simulation. +2. **Check the model with forward kinematics.** Verify numerically that A's and B's axes intersect (line distance 0), that D and L come out as designed, and that the first five joints are unchanged from the original URDF. +3. **Set the new joint's zero in the servo.** Feetech servos report `Present_Position = Actual - Homing_Offset` (modulo 4096), and LeRobot's degree mode maps raw count 2047 to 0°. So pose the joint at its zero by hand, read the raw encoder value, and write `Homing_Offset = encoder - 2047`. +4. **Keep the position limits symmetric.** LeRobot takes the midpoint of the limit range as 0°, so asymmetric register limits shift the zero. Narrow the working range in the URDF instead. +5. **Recalibrate only the joints you changed.** Rerunning the full LeRobot calibration moves the zeros of joints 1 to 4 and breaks their agreement with the URDF. +6. **Keep both copies of the calibration file identical.** LeRobot loads `~/.cache/huggingface/lerobot/calibration/robots/so_follower/.json`. If that file differs from the values in the servos, `connect()` asks for confirmation and then writes the stale values back. Keep a backup in your repository and update both together. + +### Avoid the singularity and the mirror solution +With A = 0 and B = 0, A's axis is parallel to the wrist-flex axis, the two joints swing the rod in the same plane, and the 5D task Jacobian loses rank. With B turned 90° away from that, A's axis is perpendicular to the wrist-flex axis and the Jacobian is well conditioned. The IK therefore uses its spare degree of freedom to pull B toward that rest angle: wrist flex then handles pitch, A handles sideways tilt, and the wrist would only lock at A = ±90°, which is outside the limits. The configurations (B, A) and (B ± 180°, −A) point the rod the same way. Limiting B to a half-turn around its rest angle keeps only one of them, so the IK cannot jump between the two in the middle of a motion. + +> **Check joint limits before you turn on torque.** An early test script found B outside its software limits at startup, clamped the goal to the nearest limit, and drove the joint most of a turn, which wound up the cable to servo A. The encoder only knows its position within one turn, so software cannot detect a twisted cable. Read all joints first, refuse to start (and ask the user to move the arm by hand) if any joint is out of range, and set `Goal_Position` equal to `Present_Position` before enabling torque so that the arm does not jump. + +Also keep the contact force in mind. LeRobot caps the torque of the former gripper servo at 50% by default, which leaves only a few tens of newtons at the face of a short rod, and less for a longer one. Check that this is enough for your task before raising the cap; the cap also limits the damage in a collision. + +## Step 2: Solve Inverse Kinematics for a Contact Pose +The contact pose is a position plus a direction. A full 6D pose IK would also impose a roll angle that does not matter and that the arm may not be able to reach, so the solver treats the three goals with strict priorities [9], [13]. + +**Position (primary).** Damped least squares (DLS) [2] on the linear Jacobian $$J_p$$ moves the tool face toward the goal, where $$\mathbf{e}_p$$ is the position error: + +$$\Delta\mathbf{q}_1 = J_p^\top \left(J_p J_p^\top + \lambda^2 I\right)^{-1} \mathbf{e}_p$$ + +**Approach direction (secondary), in the null space of the position task.** With $$N_1 = I - J_p^{+} J_p$$, aiming never moves the tip. The error $$\mathbf{e}_r$$ is the rotation vector that turns the current tool axis $$\mathbf{z}$$ onto the approach direction $$\mathbf{a} = -\mathbf{n}$$, and $$J_\omega$$ is the angular Jacobian: + +$$\Delta\mathbf{q}_2 = N_1 (J_\omega N_1)^\top \left[(J_\omega N_1)(J_\omega N_1)^\top + \lambda^2 I\right]^{-1} \left(\mathbf{e}_r - J_\omega \Delta\mathbf{q}_1\right)$$ + +**Rest posture (tertiary), in the null space of both.** Only the two components of the angular velocity perpendicular to $$\mathbf{z}$$ are constrained, because roll about the tool axis is free. With the stacked task Jacobian below and $$N_2 = I - J_t^{+} J_t$$, the redundant DOF is pulled toward a rest configuration $$\mathbf{q}_\text{rest}$$ with gain $$k_\text{rest}$$: + +$$J_t = \begin{bmatrix} J_p \\ (I - \mathbf{z}\mathbf{z}^\top) J_\omega \end{bmatrix}, \qquad \Delta\mathbf{q}_3 = N_2\, k_\text{rest} \left(\mathbf{q}_\text{rest} - \mathbf{q}\right)$$ + +The update is $$\Delta\mathbf{q} = \Delta\mathbf{q}_1 + \Delta\mathbf{q}_2 + \Delta\mathbf{q}_3$$, clipped to the joint limits. One iteration in NumPy, given a chain object that provides `fk(q)` (4x4 tool pose) and `jacobian(q)` (6xn, linear rows first, base frame): + +```python +import numpy as np + +def dls(J, e, lam): + """Damped least squares: J^T (J J^T + lam^2 I)^-1 e.""" + return J.T @ np.linalg.solve(J @ J.T + lam**2 * np.eye(J.shape[0]), e) + +def contact_ik_step(chain, q, p_goal, a_goal, q_rest, lam=0.05, k_rot=0.5, k_rest=0.3): + """Tool face to p_goal (primary), tool +Z onto a_goal (secondary), + spare DOF toward q_rest (tertiary; NaN entries mean 'don't care').""" + T, J = chain.fk(q), chain.jacobian(q) + Jp, Jw = J[:3], J[3:] + z = T[:3, 2] # tool axis, base frame + e_p = p_goal - T[:3, 3] + c = np.cross(z, a_goal) # axis that turns z onto a_goal + s, ang = np.linalg.norm(c), np.arctan2(np.linalg.norm(c), z @ a_goal) + e_r = k_rot * min(ang, 0.3) * c / s if s > 1e-9 else np.zeros(3) + + I = np.eye(len(q)) + dq1 = dls(Jp, e_p, lam) + N1 = I - np.linalg.pinv(Jp, rcond=1e-4) @ Jp # aiming never moves the tip + dq2 = N1 @ dls(Jw @ N1, e_r - Jw @ dq1, lam) + Jt = np.vstack([Jp, (np.eye(3) - np.outer(z, z)) @ Jw]) # roll about z is free + N2 = I - np.linalg.pinv(Jt, rcond=1e-4) @ Jt + dq3 = N2 @ np.nan_to_num(k_rest * (q_rest - q)) + return np.clip(q + dq1 + dq2 + dq3, chain.lower, chain.upper) +``` + +Reasonable starting values are $$\lambda = 0.05$$, a position step limited to 0.2 rad, and up to 150 iterations. The rest vector only needs to set the wrist roll; leave the other joints free. + +### Make it robust +- **Lock joints at their limits.** When a step pushes a joint further into its limit, zero that joint's column and recompute the step, so the other joints take up its share instead of the whole solve stalling. Finish with a few position-only DLS iterations, because clipping can bend the projected steps off the position task. +- **Seed carefully.** Try the current joint angles first, then the result of a least-squares 6D pose IK (it lands in the right basin for the approach direction far more often than random seeds), then random seeds within the limits. Self-motion branches of a redundant arm only meet at singularities, which a null-space pull cannot cross, so also try each seed with its rest joints set to their rest values. +- **Rank the solutions.** Prefer converged solutions, then those within 0.5° of the approach direction, then the one closest to the rest pose. +- **Stop early.** Stop once the best answer has been found twice. Further seeds rarely improve on it, and the planning time drops substantially. +- **Reject impossible targets before running the IK.** A failing IK runs all its restarts, which takes seconds. A geometric bound takes microseconds: with the rod exactly on the normal, the last joint origin must lie within the arm's straight-line reach from the shoulder, for some pan angle. Allow a margin for the tolerated approach angle. This bound never rejects a reachable pose. +- **Use local IK for small moves.** For short steps along a path or for following a moving target, seed from the current command and use one restart, no pose seed, and few iterations, so the arm stays on the same branch. + +### Validate before trusting it +1. **Self-test from forward kinematics.** Sample random joint angles inside the limits, compute the tool pose, and solve IK for it. Expect essentially 100% convergence and sub-degree approach errors; anything less points to a bug or poor seeding. +2. **Compare forward kinematics with the real arm.** Overlay the model's tool on the camera image, or move the arm by hand and measure. Constant offsets point to joint zero errors, which Step 3 estimates. +3. **Move slowly first.** Drive the real arm with joint sliders at about 1° per control tick before letting the IK command it. + +## Step 3: Calibrate the Camera and the Arm by Touching a Board +The loop needs the transform from the camera frame to the base frame. The usual tools are AX = XB hand-eye calibration [15] and point-pair registration with the Kabsch algorithm [1], [7]: touch a target with the tool, record its position from the camera and from forward kinematics, and fit a rigid transform. Point-pair registration was the first method used in the example, and it left about 8 mm of residual error. The cause was that the arm's own joint zeros were wrong: after LeRobot's middle-of-range calibration, shoulder lift, elbow flex, and wrist flex were each off by several degrees, up to about 10° on the elbow. No rigid camera transform can absorb a joint offset, because its effect changes with the arm's pose. The solution is to calibrate the camera and the kinematics together. + +### Collect contacts that constrain position and direction +Print a calibration board with two AprilTags and a row of circles at known positions. Each circle has an inner ring the size of the rod face. Glue it to something rigid: glass, acrylic, or aluminum. Then, with torque off: + +1. Click the circle you are going to touch in the camera view. +2. Press the rod face **flat** on that circle, covering the inner ring, and hold still. +3. Capture about 10 frames and reject the capture if the arm or the board moved during them. +4. Record the joint readings, the board pose from PnP on all visible tag corners, and the depth at each tag center. + +Each capture constrains five quantities: the face center must lie on the circle (3) and the rod axis must lie along the board's inward normal (2). Collect 40 to 60 captures: every circle, two or three wrist poses per circle (rod tilted both ways, wrist roll varied), and three or four board poses (flat, tilted about 30° in two directions, near and far). Keep both tags in view where possible. Captures that see only one tag were consistently worse. + +### Fit everything together +For capture $$i$$, the board pose from the tags is $$(R_i, \mathbf{t}_i)$$ and the touched circle is at $$\mathbf{x}_i$$ in the board frame. The circle in the base frame is + +$$\mathbf{b}_i = R\, k\,(R_i \mathbf{x}_i + \mathbf{t}_i) + \mathbf{t}$$ + +where $$(R, \mathbf{t})$$ is the camera-to-base transform and $$k$$ is a tag scale factor that absorbs printing scale and tag-size error. The rod face from forward kinematics on the joint readings plus zero offsets $$\boldsymbol{\delta}$$ must coincide with it. The unknowns are $$R$$, $$\mathbf{t}$$, $$k$$, small corrections to D and L, and zero offsets for every joint except the pan, whose offset the camera rotation absorbs. They are solved with Levenberg-Marquardt [8], with angles weighted against positions (0.05 m/rad is a reasonable start): + +```python +def capture_residual(p, cap, chain, w_ang=0.05): + """p = [camera->base rotation vector (3), translation (3), log k, zero offsets (5)].""" + R, t, k = rotvec_to_matrix(p[0:3]), p[3:6], np.exp(p[6]) + q = cap.q_reading + np.concatenate([[0.0], p[7:12]]) # pan offset not identifiable + T = chain.fk(q) # rod face pose, base frame + circle = R @ (k * (cap.R_board @ cap.x_circle + cap.t_board)) + t + inward = -R @ cap.R_board[:, 2] # board normal, pointing in + return np.concatenate([T[:3, 3] - circle, # 3 position residuals (m) + w_ang * np.cross(T[:3, 2], inward)]) # rod axis vs. normal +``` + +Stack these residuals for all captures and minimize their sum of squares. A numerical Jacobian is fast enough for about a dozen parameters and a few dozen captures. Before using real data, generate synthetic captures with known errors and noise and check that the fit recovers them to within about their estimated standard deviations. + +### Take the tag scale from the depth camera +The contacts barely determine $$k$$: fitting it or fixing it changes the residual by only a fraction of a millimeter. Its value still matters a great deal, because Step 4 plans contacts against the plane measured by the depth camera, while the target comes from the tags. In the example, a fitted $$k$$ put the depth plane about 5 mm closer to the arm than the tag plane. With a contact offset of a few millimeters, the planner then refused almost every contact as "within the clearance of the wall." Holding $$k$$ at the ratio of the measured depth to the PnP depth at the tag centers makes the two planes agree. + +### What to expect, and common pitfalls +Expect a position error of a few millimeters RMS (4 to 6 mm in the example), a leave-one-out error only slightly higher, and an axis error of a few degrees, which mostly reflects how flush the face was pressed by hand. Apply the fitted joint zero offsets in software as `model angle = servo reading + offset`, and narrow the model's joint limits so that commands stay inside the servo limits; nothing needs to be written to the servos. Lessons from the failed attempts: + +- **A flexible board ruins the fit.** The first collection used paper on a hand-held plastic lid that was not flat and flexed under the rod. The fit returned a rod about half its real length and roughly twice the usual residual. +- **Free the link lengths once to detect hardware changes.** In a later collection, the fitted rod length came out about 3 cm longer than the model in every data split. The rod had been replaced by a longer one without updating the URDF. +- **Check the print scale.** An A4 board printed "fit to page" on US Letter paper comes out at 94% scale. Measure a printed scale bar and a tag, and write the measured layout into the board description. A uniform scale error is absorbed by $$k$$, but a mismatch between tag size and layout is not. +- **Look for single outliers.** A capture tens of millimeters off the rest usually means the wrong circle was clicked. Exclude it and refit, and report the leave-one-out error so that a single capture cannot hide a bad fit. +- **Verify visually.** Draw the model's rod on the live video. It should sit on the real rod everywhere in the workspace. Then hover the rod about 20 mm above a few circles before allowing any contact. + +## Step 4: Estimate the Wall from Tags and Depth +The loop needs two things from each frame: the plane the arm must not hit, and the target point on that plane. Fiducials and depth are each good at one of them, so the example uses both. + +### Board pose from all visible tags +Detect tag36h11 tags with OpenCV's ArUco module (`DICT_APRILTAG_36h11`, AprilTag corner refinement) [11]. Search for quads on a half-size image (`aprilTagQuadDecimate = 2`). This cut detection on a 1280x720 frame from about 70 ms to about 17 ms on a laptop. Undistort the corners, then solve one PnP problem on the corners of all visible tags at their printed positions in the board frame. Use SQPnP [14] followed by iterative refinement. IPPE, which OpenCV uses for single square markers, tilted an almost fronto-parallel board by several degrees. Filter the pose with an exponential moving average, and ignore single-frame jumps (for example, larger than 5 cm or 20°) unless they persist for several frames. + +To keep the cost independent of the board's size, predict where each tag will appear from the last pose and search only small windows around the few tags nearest the target. Search the whole frame only after the board was lost. Make the board larger than the camera's field of view, with tags spread over it, so that some tags stay visible as the base moves and the arm covers others. + +### The wall plane from depth +Deproject every eighth pixel of the color-aligned depth image, transform the points into the base frame, and fit a plane. The thresholds below are the starting values used in the example: + +- **Mask the arm.** Remove points within about 4 cm of the arm's skeleton from forward kinematics, so the rod touching the wall cannot pull the fit toward itself. +- **Acquire through the target.** For the first fit, make every RANSAC [4] hypothesis pass through the target point. Floors and tables in view then cannot win. Reject fits tilted more than about 60° from the optical axis. +- **Track within a band.** On later frames, fit only points within about 5 cm of the last plane, and reject fits that turn more than about 15°. No target is needed, so the wall is still tracked while the arm covers the tags. Refine the best hypothesis with least squares on its inliers. +- **Add hysteresis.** Replace the stored plane only when the fit moves more than about 2 mm or 0.5°. Depth noise then does not change the plane every frame, and "the plane changed" can be used as the signal to re-check the current path. +- **Give up cleanly.** After a few failed fits in a row, drop the plane and wait for the target to acquire it again. + +All of this takes only a few milliseconds per frame in NumPy. Use the D435's 848x480 depth mode: at 1280x720 the minimum range grows to about 28 cm, too far for a rod that works close to the camera. Put the camera on USB 3; over USB 2 the 30 fps color and depth modes are not available. + +### Snap the tags onto the depth plane +Thousands of depth points give a much better plane than a few tag corners, and the planner checks the arm against the depth plane anyway. So the example lays the board frame onto the depth plane and uses the tags only to place the target within it. The board frame is rotated so that its normal matches the plane's, and it is moved along the camera ray onto the plane. Do this at the **pivot**, the center of the tags currently in view, not at the board origin. A tilt error moves a point by the tilt times its distance from the tags that produced the pose. On a large board, 2° at 0.6 m is about 2 cm. + +```python +def snap_to_wall(R_b, t_b, k, pivot, wall_n, wall_p0, cam, max_deg=12.0, max_m=0.025): + """Board frame (x_base = t_b + k R_b x) laid onto the depth plane, or None. + pivot: board-frame center of the tags in view; cam: camera position (base frame).""" + a, b = R_b[:, 2], wall_n + p = t_b + k * R_b @ pivot + if np.degrees(np.arccos(np.clip(a @ b, -1, 1))) > max_deg or abs(b @ (p - wall_p0)) > max_m: + return None # tags and depth disagree: skip frame + v, c = np.cross(a, b), a @ b + V = np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]]) + turn = np.eye(3) + V + V @ V / (1.0 + c) # smallest rotation taking a onto b + ray = p - cam + s = (b @ (wall_p0 - cam)) / (b @ ray) # pivot slid along the ray onto the plane + R_new = turn @ R_b + return R_new, cam + s * ray - k * R_new @ pivot +``` + +The disagreement check is a useful health monitor. With a still board and three tags in view, the tags and the depth plane should agree to about 1 mm and 0.2°. With one tag, expect about 2 mm and 2°. If they disagree by more than a few centimeters or about 10°, skip the frame. If that keeps happening for half a second or so, the depth fit has probably locked onto another surface, so drop it and acquire it again. + +## Step 5: Plan the Contact Approach +A contact motion has three parts (Figure 2): a transit from wherever the arm is to a **pre-contact** pose a few centimeters out along the normal, a straight **approach** along the normal to the contact offset, and later the same line in reverse to **back out**. + +![Side view of one contact: transit from home to the pre-contact pose, straight approach along the normal, contact offset, and the clearance band near the wall](/assets/images/visual-servoing-contact-approach.png) +*Figure 2. The three parts of a contact motion, with the starting values used in the example. Only the last few centimeters of the rod may enter the body clearance band.* + +### Plan backward from the contact +1. **Pre-check reach** with the geometric bound from Step 2. +2. **Solve the contact pose first:** face at $$\mathbf{p} + d\,\mathbf{n}$$, axis along $$-\mathbf{n}$$, spare DOF pulled to the rest pose. Refuse it if the axis is more than a few degrees off the normal, or if the arm violates the wall clearance in that pose. +3. **Build the straight line backward,** from the contact pose out to the standoff. Solve IK every few millimeters, seeded from the previous solution, and shorten the step where the joints move quickly. End the line if a step misses its point by more than about 1 mm (a joint limit) or needs a joint to jump by more than about 10° (a branch flip). Near the joint limits, accept a shorter line rather than none. +4. **Plan the transit** from the current configuration to the start of that line. + +Planning backward guarantees that the line ends exactly on the contact branch. Planning forward from an arbitrary pre-contact pose can end on a branch from which the arm cannot continue straight to the wall. + +### Check the arm against the wall +- **Model the arm as points.** Sample points every 2 cm or so along the segments between consecutive joint origins, plus the tool tip. This is much cheaper than mesh collision checking and adequate with a margin. +- **Use two clearances.** The arm body must stay a safe distance from the wall plane (3 cm in the example), which covers link thickness and calibration error. Only the last few centimeters of the chain, the end of the rod, may come closer. Keep their clearance below the contact offset so that depth noise does not reject every contact. +- **Check paths densely.** Paths are straight lines in joint space with all joints interpolated together, checked about every 1° of joint motion, not only at their endpoints. +- **Let the arm escape.** If a path starts in violation, for example because the wall just moved closer, accept it as long as the violation never grows and, once clear, the arm stays clear. Otherwise the planner could never back the arm out. +- **Try candidate transits in order.** Try a direct joint-space move first. Then try retreating along the normal before moving across. Then try a detour through the home pose. Use the first candidate that passes the check, and refuse the target if none does. + +Planning with numerical IK can take from a fraction of a second to several seconds, especially on an embedded computer. Run it in a separate worker process so that video, wall tracking, and safety checks keep running while the arm holds its pose. Cancel a plan as soon as the operator selects a different target. + +## Step 6: Close the Loop with a Contact State Machine +Every frame, the loop measures the target and the wall again (Step 4) and advances a small state machine. Table 3 summarizes it. The thresholds are the starting values used in the example. + +**Table 3.** States of the contact sequencer. + +| State | What the arm does | Leaves when | +|---|---|---| +| Plan | Holds; the worker process plans the contact (Step 5) | Plan ready, or refused (then retried a few times, with the reason shown to the operator) | +| Transit | Follows the wall-safe path to the pre-contact pose | Arrived; if the target moves more than 5 mm or 1°, the end of the path is re-aimed on the move | +| Approach | Moves straight in along the normal at reduced speed | Face at the contact offset | +| Contact | Holds the offset and follows the target as the wall or base moves | Target released or switched, or a jump larger than 5 cm or 10° | +| Back out | Moves straight out along the normal | At the standoff, then replans or goes home | +| Lost | Holds when the board is out of view; backs out and goes home after a few seconds | Board visible again soon enough (resume), else target dropped | + +### Follow a moving target +- **At contact,** re-aim a few times per second when the target has moved more than the follow threshold. Use one IK solve seeded from the current command, and move straight in joint space if no joint moves far and the path passes the wall check. Otherwise use a short Cartesian line that keeps the rod on the normal. Larger jumps back out and replan. +- **During transit,** re-solve the contact and pre-contact poses locally from the planned ones, and reject them if any joint would move far. Continue toward the new pre-contact pose without stopping. If that fails and the target has moved more than a couple of centimeters, replan while the arm keeps moving, and join the new plan from wherever the arm is when the plan arrives. Stop and replan only if the updated wall cuts into the rest of the path. +- **Near the wall,** the arm itself often hides the tags. If the board disappears during the approach, finish onto the last known point rather than aborting. + +### Execute paths faithfully +- **Stream the path; never send only its end.** Each servo moves to its goal at its own speed, so a single far goal produces a different, unchecked path. Advance a setpoint along the densified path with all joints moving together. +- **Advance by time, not by ticks.** Move faster along transits than on the straight lines into and along the wall (50°/s and 20°/s of joint motion in the example), and compute the advance from the time since the last tick, so that a slow frame does not slow the arm. Never skip a waypoint in one tick, so the command stays on the polyline that was checked. +- **Wait for the arm.** If any joint lags its command by more than about 10°, stop advancing, and do not try to catch up afterward. A runaway setpoint pulls the arm off the checked path. +- **Fight gravity sag.** LeRobot's SO-101 defaults use no integral gain, so loaded joints droop. As a starting point, the example raises the (P, I, D) gains of shoulder lift to (25, 15, 32) and of elbow flex to (20, 15, 32) at startup. Wrist flex still has no integral term, so the rod tends to land low on surfaces facing upward. Log the gap that the joint readings imply at contact, and the per-joint difference between command and reading, then raise the contact offset or add integral gain on that joint. + +### Layer the safety measures +- **Back away from an approaching wall.** If the wall moves into the arm's clearance while it holds, back away along the normal with the rod axis kept. At contact, back out as soon as the wall comes a couple of millimeters into the clearance. +- **Refuse rather than guess.** Without a wall estimate the arm does not go to the target. With no safe path it holds. +- **Run a watchdog process.** The servo loop sends a heartbeat every tick to a separate guard process. If the loop crashes or goes silent for several seconds, the guard kills it, opens the motor bus itself, backs the rod out along the last normal, steps home, and releases torque. +- **Make every shutdown path safe.** Handle the stop key, termination signals, and errors inside the loop the same way: back out, go home, then quit. Give that sequence enough time to finish; a hard kill of the process skips it. +- **Stop on lost links.** A remote operator link should carry heartbeats, and a few seconds of silence should count as a stop. On a mobile base, a hardware switch (for example an RC channel on the flight controller) can act as a master stop on top of it. +- **Know what software cannot fix.** If the servos lose power or trip their overload protection, they stop answering on the bus and nothing in software can move the arm. Power-cycle them after checking for a collision. + +### Validate in stages +1. **Offline self-test.** Simulate the arm on the calibrated chain with a board that drifts slowly, jumps, is hidden briefly and for longer, is switched, and is out of reach. Check the face error, the rod's angle to the normal, and the arm's minimum clearance to the wall over the whole run. +2. **Synthetic camera.** Drive the full program with rendered color and depth frames, a fake arm, and scripted clicks. This checks the glue code: the depth plane should land on the tag plane, and the contact at the commanded offset. +3. **Hover test on hardware.** Hold the rod about 20 mm above circles and compare the model's rod with the real one on the video. +4. **First contacts.** Start with a 2 cm contact offset, watch the logged gap at contact, then reduce it to the final offset. +5. **Planning regressions.** Log the inputs of every plan and replay them offline after code changes to compare planning time and outcomes. + +## Troubleshooting +**Table 4.** Common symptoms, likely causes, and what to check. + +| Symptom | Likely cause | What to check or change | +|---|---|---| +| Most contacts refused as "within the clearance of the wall" | Tag plane and depth plane disagree, often because the tag scale was fitted | Agreement numbers from Step 4; recalibrate with the tag scale taken from depth | +| Contacts consistently a few centimeters off in one direction | Joint zero offsets not modeled; camera-only calibration | Fit joint zero offsets with the camera (Step 3) | +| Calibration fit gives absurd link lengths | Board flexing, or the hardware changed (e.g., new rod) | Rigid board; fit L once with it free and compare with the URDF | +| One capture far off the others | Wrong circle clicked | Exclude it; check the leave-one-out error | +| Rod lands low, or presses into an upward-facing surface | Gravity sag on joints without integral gain | Logged per-joint sag; raise contact offset or add I gain | +| "The rod only gets within N° of the normal" | Point outside the arm's dexterous workspace | Choose another point or move the base closer | +| Arm swings into a very different configuration | IK switched branches | Warm-start IK; keep the rest pose; limit the wrist roll to a half-turn | +| Camera fails to start with "Couldn't resolve requests" | D435 connected over USB 2 | USB 3 port and cable, no USB 2 hub | +| Tags blur or drop out while the base moves | Long auto exposure | Fixed short exposure with gain; keep the mean gray level above about 40 | +| Arm goes limp, every servo stops responding | Servo power dropped or overload protection tripped | Inspect for a collision, then power-cycle the servos | +| Cable wound up after starting a script | Script drove a joint from outside its limits to a clamped goal | Check limits before torque on; untwist by hand | +| Old calibration restored after `connect()` | LeRobot cache file differs from the servos | Keep the cache file and the backup identical | + +## Summary +Perpendicular contact turns visual servoing from "move the tip to a point" into a five-dimensional problem, and each stage of the pipeline has to respect that. First check that the arm can produce the required approach directions, and add a joint if it cannot. Solve IK with strict priorities: position first, approach direction in its null space, and the spare degree of freedom away from singularities. Calibrate the camera and the arm's joint zeros together from flush contacts on a rigid board, and take the tag scale from the depth camera so that tags and depth agree. In the loop, let the depth plane define the wall and the tags place the target on it, plan the contact pose first and walk backward to a standoff, and execute paths with rate limits and lag checks. Surround all of this with layers of safety that back the arm out of the wall before anything else. + +Natural next steps are force sensing at the rod (or current sensing in the servos) to close the last millimeters on force instead of position, a learned detector that replaces the fiducial board with natural surface features, a general motion planner for cluttered scenes, and coordinating the arm with the drone's position controller so that the base itself helps absorb large disturbances [10]. + +## See Also: +- [Visual Servoing](/wiki/state-estimation/visual-servoing/) +- [Hand-Eye Calibration](/wiki/sensing/handeye-calibration/) +- [Hand-Eye Calibration with easy_handeye](/wiki/sensing/easy-handeye/) +- [Comparison of Fiducial Markers](/wiki/sensing/fiducial-markers/) +- [Intel RealSense](/wiki/sensing/realsense/) +- [Camera Calibration](/wiki/sensing/camera-calibration/) +- [Task Prioritization Control for Advanced Manipulator Control](/wiki/actuation/task-prioritization-control/) +- [Resolved-Rate Motion Control](/wiki/planning/resolved-rates/) +- [Manipulator Trajectory Planning using CuRoBo](/wiki/planning/curobo-trajectory-planning/) + +## Further Reading +- Seeed Studio, [Getting Started with SO-ARM100 and SO-ARM101 in LeRobot](https://wiki.seeedstudio.com/lerobot_so100m_new/) +- Hugging Face, [LeRobot SO-101 documentation](https://huggingface.co/docs/lerobot/so101) +- TheRobotStudio, [SO-ARM100 hardware repository](https://github.com/TheRobotStudio/SO-ARM100) (STL files, URDF and MJCF models) +- Intel, [RealSense SDK 2.0 (librealsense)](https://github.com/IntelRealSense/librealsense) +- OpenCV, [Detection of ArUco markers](https://docs.opencv.org/4.x/d5/dae/tutorial_aruco_detection.html) +- University of Michigan APRIL Lab, [AprilTag](https://april.eecs.umich.edu/software/apriltag) +- Inria, [ViSP, the Visual Servoing Platform](https://visp.inria.fr/) + +## References +[1] K. S. Arun, T. S. Huang, and S. D. Blostein, "Least-squares fitting of two 3-D point sets," *IEEE Trans. Pattern Anal. Mach. Intell.*, vol. PAMI-9, no. 5, pp. 698–700, 1987. + +[2] S. R. Buss, "Introduction to inverse kinematics with Jacobian transpose, pseudoinverse and damped least squares methods," Univ. of California, San Diego, Tech. Rep., 2004. + +[3] F. Chaumette and S. Hutchinson, "Visual servo control, Part I: Basic approaches," *IEEE Robot. Autom. Mag.*, vol. 13, no. 4, pp. 82–90, 2006. + +[4] M. A. Fischler and R. C. Bolles, "Random sample consensus: A paradigm for model fitting with applications to image analysis and automated cartography," *Commun. ACM*, vol. 24, no. 6, pp. 381–395, 1981. + +[5] Hugging Face, "LeRobot: State-of-the-art machine learning for real-world robotics in PyTorch." [Online]. Available: https://github.com/huggingface/lerobot + +[6] S. Hutchinson, G. D. Hager, and P. I. Corke, "A tutorial on visual servo control," *IEEE Trans. Robot. Autom.*, vol. 12, no. 5, pp. 651–670, 1996. + +[7] W. Kabsch, "A solution for the best rotation to relate two sets of vectors," *Acta Crystallogr. A*, vol. 32, no. 5, pp. 922–923, 1976. + +[8] D. W. Marquardt, "An algorithm for least-squares estimation of nonlinear parameters," *J. Soc. Ind. Appl. Math.*, vol. 11, no. 2, pp. 431–441, 1963. + +[9] Y. Nakamura, H. Hanafusa, and T. Yoshikawa, "Task-priority based redundancy control of robot manipulators," *Int. J. Robot. Res.*, vol. 6, no. 2, pp. 3–15, 1987. + +[10] A. Ollero, M. Tognon, A. Suarez, D. Lee, and A. Franchi, "Past, present, and future of aerial robotic manipulators," *IEEE Trans. Robot.*, vol. 38, no. 1, pp. 626–645, 2022. + +[11] E. Olson, "AprilTag: A robust and flexible visual fiducial system," in *Proc. IEEE Int. Conf. Robot. Autom. (ICRA)*, 2011, pp. 3400–3407. + +[12] Seeed Studio, "Getting started with SO-ARM100 and SO-ARM101 robotic arms in LeRobot." [Online]. Available: https://wiki.seeedstudio.com/lerobot_so100m_new/ + +[13] B. Siciliano and J.-J. E. Slotine, "A general framework for managing multiple tasks in highly redundant robotic systems," in *Proc. 5th Int. Conf. Adv. Robot. (ICAR)*, 1991, pp. 1211–1216. + +[14] G. Terzakis and M. Lourakis, "A consistently fast and globally optimal solution to the perspective-n-point problem," in *Proc. Eur. Conf. Comput. Vis. (ECCV)*, 2020, pp. 478–494. + +[15] R. Y. Tsai and R. K. Lenz, "A new technique for fully autonomous and efficient 3D robotics hand/eye calibration," *IEEE Trans. Robot. Autom.*, vol. 5, no. 3, pp. 345–358, 1989.