Always Verify FK After IK
Put the joint angles from IK back into FK and check that the end-effector lands on the target.
A robot can only turn its joints, but the work is at a point in space: a weld seam, a screw hole, a part on a tray. With the wrong joint angles the tool arrives a few millimetres away and the weld is scrap. Two calculations connect the angles to the point. Forward kinematics (FK) answers “the joints are at these angles, so where is the tool?” Inverse kinematics (IK) answers “the tool must be at this point, so which angles do I command?” This lesson solves both for a two-link welding arm. #ForwardKinematics #InverseKinematics #RoboticWelding
By the end of this lesson, you will be able to:
A robot arm welds a curved seam on a pressure vessel. The arm moves in one flat plane and has two revolute (turning) joints, so it is called a planar 2R arm. Its link lengths are
A torch that is off the seam gives a weld that is not fully fused or burns through the plate. The controller uses inverse kinematics to turn the next point of the seam into joint angles, and forward kinematics to check from the measured angles that the torch arrived.
The joint angles are known. Where is the end-effector (the tool at the end of the arm)? We answer first for the planar 2R arm with plain trigonometry, then with a method that works for any number of joints.
Link 1 has length
Walk from the base to the hand. A link of length
Add link 2 to reach the end-effector:
Every pair
Worked example. Take
The elbow is at (282.8, 282.8) mm and the torch is at (572.6, 360.5) mm ✅
The program repeats the worked example and prints the same two positions.
import numpy as npimport matplotlib.pyplot as plt
def forward_kinematics_2R(L1, L2, theta1, theta2): """Compute end-effector position for a 2R planar robot.
Args: L1: Length of link 1 (mm) L2: Length of link 2 (mm) theta1: Joint 1 angle (radians), measured from +x axis theta2: Joint 2 angle (radians), relative to link 1
Returns: (x_e, y_e): End-effector position in base frame (mm) (x_1, y_1): Elbow position in base frame (mm) """ # Elbow (joint 2) position x1 = L1 * np.cos(theta1) y1 = L1 * np.sin(theta1)
# End-effector position x_e = x1 + L2 * np.cos(theta1 + theta2) y_e = y1 + L2 * np.sin(theta1 + theta2)
return (x_e, y_e), (x1, y1)
# Example: L1 = 400mm, L2 = 300mmL1, L2 = 400, 300theta1 = np.radians(45) # 45 degreestheta2 = np.radians(-30) # -30 degrees relative to link 1
(x_e, y_e), (x1, y1) = forward_kinematics_2R(L1, L2, theta1, theta2)print(f"Elbow: ({x1:.1f}, {y1:.1f}) mm")print(f"End-effector: ({x_e:.1f}, {y_e:.1f}) mm")def plot_robot_2R(L1, L2, theta1, theta2, target=None, title="2R Robot Arm"): """Visualize a 2R planar robot configuration.
Args: L1, L2: Link lengths (mm) theta1, theta2: Joint angles (radians) target: Optional (x, y) target point to display title: Plot title """ (x_e, y_e), (x1, y1) = forward_kinematics_2R(L1, L2, theta1, theta2)
fig, ax = plt.subplots(1, 1, figsize=(8, 8))
# Draw links ax.plot([0, x1], [0, y1], 'b-o', linewidth=3, markersize=8, label='Link 1') ax.plot([x1, x_e], [y1, y_e], 'r-o', linewidth=3, markersize=8, label='Link 2')
# Base joint ax.plot(0, 0, 'ks', markersize=12, label='Base')
# End-effector ax.plot(x_e, y_e, 'g^', markersize=14, label='End-effector')
# Workspace boundary circles r_max = L1 + L2 r_min = abs(L1 - L2) circle_outer = plt.Circle((0, 0), r_max, fill=False, linestyle='--', color='gray', alpha=0.5) circle_inner = plt.Circle((0, 0), r_min, fill=False, linestyle='--', color='gray', alpha=0.5) ax.add_patch(circle_outer) ax.add_patch(circle_inner)
if target is not None: ax.plot(target[0], target[1], 'rx', markersize=15, markeredgewidth=3, label='Target')
ax.set_xlim(-r_max * 1.2, r_max * 1.2) ax.set_ylim(-r_max * 1.2, r_max * 1.2) ax.set_aspect('equal') ax.grid(True, alpha=0.3) ax.legend(loc='upper left') ax.set_xlabel('x (mm)') ax.set_ylabel('y (mm)') ax.set_title(title) plt.tight_layout() plt.savefig("robot_2R_config.png", dpi=150) plt.show()
# plot_robot_2R(L1, L2, theta1, theta2,# title=f"2R Arm: θ1={np.degrees(theta1):.0f}°, θ2={np.degrees(theta2):.0f}°")With six joints in 3D, the walk from base to hand is long and mistakes are easy. The Denavit-Hartenberg (DH) method replaces it with a table. You fix a frame (an origin with
| Parameter | Symbol | Description |
|---|---|---|
| Joint angle | Turn about | |
| Link offset | Slide along | |
| Link length | Slide along | |
| Link twist | Turn about |
A revolute joint changes
The four moves, done in the order of the table, are written as one
Forward kinematics is then one multiplication, in order from the base to the end-effector (ee), for an arm with
The last column of the result holds the position of the end-effector.
In our planar arm all joint axes are parallel, so
def dh_transform(theta, d, a, alpha): """Compute the 4x4 DH transformation matrix.
Args: theta: Joint angle (rad) d: Link offset (mm) a: Link length (mm) alpha: Link twist (rad)
Returns: 4x4 numpy array (homogeneous transformation) """ ct, st = np.cos(theta), np.sin(theta) ca, sa = np.cos(alpha), np.sin(alpha)
return np.array([ [ct, -st * ca, st * sa, a * ct], [st, ct * ca, -ct * sa, a * st], [0, sa, ca, d ], [0, 0, 0, 1 ] ])
def fk_from_dh(dh_table, joint_angles): """Compute FK from a DH parameter table.
Args: dh_table: List of (a, alpha, d, theta_offset) for each joint joint_angles: List of joint angle values (rad)
Returns: 4x4 homogeneous transformation (base to end-effector) """ T = np.eye(4) for i, (a, alpha, d, theta_offset) in enumerate(dh_table): theta = joint_angles[i] + theta_offset T = T @ dh_transform(theta, d, a, alpha) return T
# DH table for 2R planar robot# (a, alpha, d, theta_offset)dh_2R = [ (400, 0, 0, 0), # Link 1: a=400mm, planar (300, 0, 0, 0), # Link 2: a=300mm, planar]
# Test: same angles as beforeq = [np.radians(45), np.radians(-30)]T = fk_from_dh(dh_2R, q)print(f"End-effector position from DH: ({T[0,3]:.1f}, {T[1,3]:.1f}) mm")In most six-joint industrial robots, the first three joints place the wrist and the last three turn the tool. The maker publishes the DH table of each model.
Inverse kinematics is the harder question: from a known target position
Touch a point on the table with one fingertip: your elbow can be high or low, and the fingertip does not move. A two-link arm has the same choice, with two solutions for a target inside the reachable region, one for a target exactly on its edge, and none outside it.
The two solutions are mirror images in the line from base to target, and are named by where the elbow sits. For a target to the right of the base, as in all examples here:
A welding path must stay with one of the two. A change from one to the other in the middle of a seam swings the whole arm across.
The geometric method is an exact formula for simple arms. The numerical method corrects a guess step by step and works for any arm.
The base, the elbow and the target make a triangle. Two sides are the links,
Step 1: Solve for
By Pythagoras, the distance from the base to the target is given by:
The law of cosines relates the three sides of a triangle to one of its angles. The angle inside the triangle at the elbow is
Solve for
A cosine lies between
The positive value is the elbow-down solution and the negative value is the elbow-up solution.
For the target (500, 200) mm with
Step 2: Solve for
The angle
Then:
For the target (500, 200) mm,
The program solves the same target and checks each solution with forward kinematics.
def inverse_kinematics_2R(L1, L2, x_t, y_t): """Geometric IK for a 2R planar robot.
Args: L1, L2: Link lengths (mm) x_t, y_t: Target position (mm)
Returns: List of (theta1, theta2) solution tuples (radians). Returns empty list if target is unreachable. """ r_sq = x_t**2 + y_t**2 r = np.sqrt(r_sq)
# Check reachability r_max = L1 + L2 r_min = abs(L1 - L2) if r > r_max or r < r_min: print(f"Target ({x_t:.1f}, {y_t:.1f}) is unreachable.") print(f" Distance: {r:.1f} mm") print(f" Reachable range: [{r_min:.1f}, {r_max:.1f}] mm") return []
# Solve for theta2 cos_theta2 = (r_sq - L1**2 - L2**2) / (2 * L1 * L2) # Clamp for numerical safety cos_theta2 = np.clip(cos_theta2, -1.0, 1.0) sin_theta2 = np.sqrt(1 - cos_theta2**2)
solutions = [] # sign +1 gives theta2 > 0, sign -1 gives theta2 < 0. for sign in [+1, -1]: # elbow-down (theta2 > 0), elbow-up (theta2 < 0) s2 = sign * sin_theta2 theta2 = np.arctan2(s2, cos_theta2)
# Solve for theta1 k1 = L1 + L2 * cos_theta2 k2 = L2 * s2 theta1 = np.arctan2(y_t, x_t) - np.arctan2(k2, k1)
solutions.append((theta1, theta2))
return solutions
# Test: find joint angles for target (500, 200)L1, L2 = 400, 300target = (500, 200)solutions = inverse_kinematics_2R(L1, L2, *target)
for i, (t1, t2) in enumerate(solutions): config = "Elbow-down" if t2 > 0 else "Elbow-up" print(f"Solution {i+1} ({config}):") print(f" theta1 = {np.degrees(t1):.2f} deg") print(f" theta2 = {np.degrees(t2):.2f} deg")
# Verify with FK (xe, ye), _ = forward_kinematics_2R(L1, L2, t1, t2) print(f" FK check: ({xe:.2f}, {ye:.2f}) mm") error = np.sqrt((xe - target[0])**2 + (ye - target[1])**2) print(f" Position error: {error:.6f} mm")def plot_ik_solutions(L1, L2, x_t, y_t): """Plot both IK solutions (elbow-up and elbow-down).""" solutions = inverse_kinematics_2R(L1, L2, x_t, y_t) if not solutions: print("No solutions to plot.") return
fig, axes = plt.subplots(1, 2, figsize=(14, 6))
for idx, (t1, t2) in enumerate(solutions): ax = axes[idx] config = "Elbow-down" if t2 > 0 else "Elbow-up"
(xe, ye), (x1, y1) = forward_kinematics_2R(L1, L2, t1, t2)
# Links ax.plot([0, x1], [0, y1], 'b-o', linewidth=3, markersize=8) ax.plot([x1, xe], [y1, ye], 'r-o', linewidth=3, markersize=8) ax.plot(0, 0, 'ks', markersize=12) ax.plot(xe, ye, 'g^', markersize=14) ax.plot(x_t, y_t, 'rx', markersize=15, markeredgewidth=3)
# Workspace boundary r_max = L1 + L2 r_min = abs(L1 - L2) ax.add_patch(plt.Circle((0, 0), r_max, fill=False, linestyle='--', color='gray', alpha=0.4)) ax.add_patch(plt.Circle((0, 0), r_min, fill=False, linestyle='--', color='gray', alpha=0.4))
ax.set_xlim(-r_max * 1.2, r_max * 1.2) ax.set_ylim(-r_max * 1.2, r_max * 1.2) ax.set_aspect('equal') ax.grid(True, alpha=0.3) ax.set_xlabel('x (mm)') ax.set_ylabel('y (mm)') ax.set_title(f'{config}: θ1={np.degrees(t1):.1f}°, θ2={np.degrees(t2):.1f}°')
plt.tight_layout() plt.savefig("ik_solutions.png", dpi=150) plt.show()
# plot_ik_solutions(400, 300, 500, 200)Many arms have no exact formula. The numerical method needs only forward kinematics. It works the way you park a car: see how far you are from the mark, correct, and look again. This scheme is called Newton-Raphson iteration.
In the steps below,
Start with a first guess
Use forward kinematics to find where the end-effector is now:
Find the miss, from the current position to the target:
If the length of the miss
Compute the Jacobian matrix
Find the change of joint angles that removes the miss:
Apply it:
Repeat from step 2.
The Jacobian matrix
So
For the target (500, 200) mm and the default first guess, the program arrives in 6 corrections at
def jacobian_2R(L1, L2, theta1, theta2): """Compute the 2x2 Jacobian for a 2R planar robot.
Args: L1, L2: Link lengths (mm) theta1, theta2: Joint angles (rad)
Returns: 2x2 numpy array (Jacobian matrix) """ s1 = np.sin(theta1) c1 = np.cos(theta1) s12 = np.sin(theta1 + theta2) c12 = np.cos(theta1 + theta2)
J = np.array([ [-L1 * s1 - L2 * s12, -L2 * s12], [ L1 * c1 + L2 * c12, L2 * c12] ]) return J
def numerical_ik_2R(L1, L2, x_t, y_t, q0=None, tol=1e-6, max_iter=100, damping=1e-4): """Numerical IK using damped Jacobian iteration.
Args: L1, L2: Link lengths (mm) x_t, y_t: Target position (mm) q0: Initial joint angle guess (rad). Defaults to [0.5, 0.5]. tol: Convergence tolerance (mm) max_iter: Maximum iterations damping: Damping factor for singularity robustness
Returns: (theta1, theta2): Joint angles (rad), or None if no convergence history: List of (iteration, error) tuples """ if q0 is None: q0 = np.array([0.5, 0.5]) else: q0 = np.array(q0, dtype=float)
q = q0.copy() target = np.array([x_t, y_t]) history = []
for i in range(max_iter): # Current end-effector position (xe, ye), _ = forward_kinematics_2R(L1, L2, q[0], q[1]) current = np.array([xe, ye])
# Position error dp = target - current error = np.linalg.norm(dp) history.append((i, error))
if error < tol: print(f"Converged in {i} iterations (error: {error:.2e} mm)") return tuple(q), history
# Jacobian at current configuration J = jacobian_2R(L1, L2, q[0], q[1])
# Damped least-squares inverse (Levenberg-Marquardt) # Avoids singularity issues JtJ = J.T @ J + damping * np.eye(2) dq = np.linalg.solve(JtJ, J.T @ dp)
q += dq
print(f"Warning: did not converge after {max_iter} iterations") print(f" Final error: {error:.4f} mm") return tuple(q), history
# Test numerical IKL1, L2 = 400, 300target = (500, 200)
print("=== Numerical IK ===")q_numerical, hist = numerical_ik_2R(L1, L2, *target)
if q_numerical: t1, t2 = q_numerical print(f" theta1 = {np.degrees(t1):.2f} deg") print(f" theta2 = {np.degrees(t2):.2f} deg")
# Verify (xe, ye), _ = forward_kinematics_2R(L1, L2, t1, t2) print(f" FK check: ({xe:.2f}, {ye:.2f}) mm")def plot_ik_convergence(history, title="Numerical IK Convergence"): """Plot the convergence history of numerical IK.
Args: history: List of (iteration, error) tuples title: Plot title """ iters = [h[0] for h in history] errors = [h[1] for h in history]
fig, ax = plt.subplots(1, 1, figsize=(8, 5)) ax.semilogy(iters, errors, 'b-o', markersize=4) ax.axhline(y=1e-6, color='r', linestyle='--', label='Tolerance') ax.set_xlabel('Iteration') ax.set_ylabel('Position Error (mm)') ax.set_title(title) ax.legend() ax.grid(True, alpha=0.3) plt.tight_layout() plt.savefig("ik_convergence.png", dpi=150) plt.show()
# plot_ik_convergence(hist)The numerical method returns one solution, and the first guess decides which one: usually the pose nearest to the guess. A poor guess can end at the pose you did not want, or fail to settle.
The program below tries four guesses for the target (400, 300) mm. Three end at
# Demonstrate that different initial guesses yield different solutionsL1, L2 = 400, 300target = (400, 300)
initial_guesses = [ ([0.3, 0.3], "Small positive angles"), ([1.0, -1.0], "Elbow-up bias"), ([0.8, 1.2], "Elbow-down bias"), ([-0.5, 2.0], "Negative theta1"),]
print(f"Target: ({target[0]}, {target[1]}) mm\n")for q0, label in initial_guesses: result, _ = numerical_ik_2R(L1, L2, *target, q0=q0, tol=1e-6) if result: t1, t2 = result config = "elbow-down" if t2 > 0 else "elbow-up" print(f" {label}: theta1={np.degrees(t1):.1f} deg, " f"theta2={np.degrees(t2):.1f} deg ({config})")The workspace of a robot is the set of all points the end-effector can reach. For a planar 2R arm it is a ring between two circles centred on the base:
If
A target in the ring has two solutions, a target exactly on either circle has one, and a target anywhere else has none. The program below marks 5,000 random poses of the welding arm and draws the two circles over them.
def plot_workspace_2R(L1, L2, n_samples=5000): """Visualize the workspace of a 2R planar robot by sampling random joint angle configurations.
Args: L1, L2: Link lengths (mm) n_samples: Number of random configurations to sample """ # Sample random joint angles theta1_samples = np.random.uniform(-np.pi, np.pi, n_samples) theta2_samples = np.random.uniform(-np.pi, np.pi, n_samples)
x_points = [] y_points = [] for t1, t2 in zip(theta1_samples, theta2_samples): (xe, ye), _ = forward_kinematics_2R(L1, L2, t1, t2) x_points.append(xe) y_points.append(ye)
fig, ax = plt.subplots(1, 1, figsize=(8, 8)) ax.scatter(x_points, y_points, s=1, alpha=0.3, c='blue')
# Analytical boundaries r_max = L1 + L2 r_min = abs(L1 - L2) circle_outer = plt.Circle((0, 0), r_max, fill=False, linewidth=2, color='red', label=f'r_max = {r_max} mm') circle_inner = plt.Circle((0, 0), r_min, fill=False, linewidth=2, color='orange', label=f'r_min = {r_min} mm') ax.add_patch(circle_outer) ax.add_patch(circle_inner)
ax.set_xlim(-r_max * 1.3, r_max * 1.3) ax.set_ylim(-r_max * 1.3, r_max * 1.3) ax.set_aspect('equal') ax.grid(True, alpha=0.3) ax.legend(loc='upper right', fontsize=11) ax.set_xlabel('x (mm)') ax.set_ylabel('y (mm)') ax.set_title(f'Workspace of 2R Robot (L1={L1}, L2={L2} mm)') plt.tight_layout() plt.savefig("workspace_2R.png", dpi=150) plt.show()
# plot_workspace_2R(400, 300)A controller should first test the target against the two circles. The function below also warns when a target is within 35 mm of either circle. Of its five test points, (710, 0) is outside by 10 mm, and (690, 0) and (80, 80) can be reached but receive the warning.
def check_reachability(L1, L2, x_t, y_t): """Check if a target point is within the workspace.
Args: L1, L2: Link lengths (mm) x_t, y_t: Target position (mm)
Returns: dict with reachability status and margin information """ r = np.sqrt(x_t**2 + y_t**2) r_max = L1 + L2 r_min = abs(L1 - L2)
reachable = r_min <= r <= r_max
# Margin: how far inside the workspace boundary outer_margin = r_max - r # positive = inside outer boundary inner_margin = r - r_min # positive = outside inner boundary
# Proximity warning boundary_threshold = 0.05 * r_max # 5% of max reach near_boundary = (outer_margin < boundary_threshold or inner_margin < boundary_threshold)
return { 'reachable': reachable, 'distance': r, 'r_max': r_max, 'r_min': r_min, 'outer_margin_mm': outer_margin, 'inner_margin_mm': inner_margin, 'near_boundary': near_boundary, }
# Test several target pointsL1, L2 = 400, 300test_points = [ (500, 200, "Interior point"), (690, 0, "Near outer boundary"), (710, 0, "Outside workspace"), (80, 80, "Near inner boundary"), (300, 400, "Moderate distance"),]
for x, y, label in test_points: result = check_reachability(L1, L2, x, y) status = "REACHABLE" if result['reachable'] else "UNREACHABLE" warning = " [NEAR BOUNDARY]" if result['near_boundary'] else "" print(f"{label}: ({x}, {y}) -> {status}{warning}") print(f" Distance: {result['distance']:.1f} mm, " f"Outer margin: {result['outer_margin_mm']:.1f} mm")The weld seam is an arc of radius 150 mm about the point (350, 250) mm, cut into 15 waypoints. For each one the program checks the reach, solves the inverse kinematics by geometry, and warns if the joint angles jump.
All 15 waypoints can be reached. The farthest is 580 mm from the base. The program selects the solution with
def welding_seam_path(cx, cy, radius, start_angle, end_angle, n_points=20): """Generate waypoints along a circular arc (weld seam).
Args: cx, cy: Center of the arc (mm) radius: Arc radius (mm) start_angle, end_angle: Arc span (degrees) n_points: Number of waypoints
Returns: List of (x, y) waypoints """ angles = np.linspace(np.radians(start_angle), np.radians(end_angle), n_points) waypoints = [(cx + radius * np.cos(a), cy + radius * np.sin(a)) for a in angles] return waypoints
def plan_weld_path(L1, L2, waypoints, elbow_config="down"): """Plan joint trajectories for a weld seam using geometric IK.
Args: L1, L2: Link lengths (mm) waypoints: List of (x, y) target positions elbow_config: "up" or "down" (preferred elbow configuration)
Returns: List of (theta1, theta2) joint angle pairs List of reachability status for each point """ joint_trajectory = [] status_list = []
# Index 0 is the solution with theta2 > 0, which is elbow-down for a target to the right. sol_idx = 0 if elbow_config == "down" else 1
for i, (x, y) in enumerate(waypoints): reach = check_reachability(L1, L2, x, y) status_list.append(reach)
if not reach['reachable']: print(f" Waypoint {i}: ({x:.1f}, {y:.1f}) UNREACHABLE") joint_trajectory.append(None) continue
solutions = inverse_kinematics_2R(L1, L2, x, y) if solutions: # Select preferred configuration idx = min(sol_idx, len(solutions) - 1) joint_trajectory.append(solutions[idx])
# Continuity check: if the chosen solution jumps far from # the previous one, the branch just flipped. For real # trajectories you would pick the solution that minimizes # joint distance from the previous configuration instead. if i > 0 and joint_trajectory[i - 1] is not None: prev = np.array(joint_trajectory[i - 1]) curr = np.array(joint_trajectory[i]) if np.linalg.norm(curr - prev) > np.pi / 2: print(f" Waypoint {i}: branch switch detected. " f"Continuous paths must not cross between " f"elbow-up and elbow-down.")
if reach['near_boundary']: print(f" Waypoint {i}: ({x:.1f}, {y:.1f}) " f"near workspace boundary " f"(margin: {reach['outer_margin_mm']:.1f} mm)") else: joint_trajectory.append(None)
return joint_trajectory, status_list
# Define the weld seam: arc on a pressure vessel# Vessel center at (350, 250), radius 150mm, arc from -30 to +60 degreesL1, L2 = 400, 300waypoints = welding_seam_path(350, 250, 150, -30, 60, n_points=15)
print("=== Weld Path Planning ===")print(f"Robot: L1={L1} mm, L2={L2} mm")print(f"Seam: {len(waypoints)} waypoints\n")
trajectory, statuses = plan_weld_path(L1, L2, waypoints, elbow_config="down")
# Display resultsprint(f"\n{'Pt':>3} {'x':>8} {'y':>8} {'θ1 (deg)':>10} {'θ2 (deg)':>10} {'Status':>12}")print("-" * 60)for i, ((x, y), q, s) in enumerate(zip(waypoints, trajectory, statuses)): if q is not None: t1_d = np.degrees(q[0]) t2_d = np.degrees(q[1]) status = "OK" if not s['near_boundary'] else "BOUNDARY" print(f"{i:3d} {x:8.1f} {y:8.1f} {t1_d:10.2f} {t2_d:10.2f} {status:>12}") else: print(f"{i:3d} {x:8.1f} {y:8.1f} {'N/A':>10} {'N/A':>10} {'UNREACHABLE':>12}")def plot_weld_path(L1, L2, waypoints, trajectory): """Visualize the robot tracing a weld seam path.
Shows the arm configuration at several waypoints along the planned trajectory. """ fig, ax = plt.subplots(1, 1, figsize=(10, 10))
r_max = L1 + L2 r_min = abs(L1 - L2)
# Workspace boundaries ax.add_patch(plt.Circle((0, 0), r_max, fill=False, linestyle='--', color='gray', alpha=0.3)) ax.add_patch(plt.Circle((0, 0), r_min, fill=False, linestyle='--', color='gray', alpha=0.3))
# Weld seam path wx = [p[0] for p in waypoints] wy = [p[1] for p in waypoints] ax.plot(wx, wy, 'r-o', markersize=5, linewidth=2, label='Weld seam')
# Draw robot at selected waypoints show_indices = [0, len(trajectory)//3, 2*len(trajectory)//3, -1] colors = ['#1f77b4', '#2ca02c', '#ff7f0e', '#d62728']
for ci, idx in enumerate(show_indices): if trajectory[idx] is None: continue t1, t2 = trajectory[idx] (xe, ye), (x1, y1) = forward_kinematics_2R(L1, L2, t1, t2)
ax.plot([0, x1], [0, y1], '-', color=colors[ci], linewidth=2, alpha=0.6) ax.plot([x1, xe], [y1, ye], '-', color=colors[ci], linewidth=2, alpha=0.6) ax.plot(x1, y1, 'o', color=colors[ci], markersize=6) ax.plot(xe, ye, '^', color=colors[ci], markersize=10, label=f'Config at waypoint {idx}')
ax.plot(0, 0, 'ks', markersize=12, label='Base') ax.set_xlim(-r_max * 0.3, r_max * 1.2) ax.set_ylim(-r_max * 0.3, r_max * 1.2) ax.set_aspect('equal') ax.grid(True, alpha=0.3) ax.legend(loc='upper left') ax.set_xlabel('x (mm)') ax.set_ylabel('y (mm)') ax.set_title('Robot Arm Tracing Weld Seam Path') plt.tight_layout() plt.savefig("weld_path_visualization.png", dpi=150) plt.show()
# plot_weld_path(L1, L2, waypoints, trajectory)Always Verify FK After IK
Put the joint angles from IK back into FK and check that the end-effector lands on the target.
Choose Elbow Configuration Deliberately
For a continuous path (welding, painting, gluing), keep one elbow configuration from start to end. A change in the middle makes the joints jump and can damage the workpiece or the robot.
Avoid Workspace Boundaries
Near the outer circle the arm is almost straight, and a small motion of the hand along the arm needs a large change of joint angles. Keep paths 5 to 10% of the reach inside the limits, or move more slowly there.
Use Damped Least-Squares for Numerical IK
The plain inverse of the Jacobian fails when the arm is straight or folded. Damped least squares adds a small term
Initial Guess Strategy
Along a path, use the solution of the last waypoint as the first guess for the next one. The solver then needs only a few corrections and stays in the same elbow configuration.
Handle Unreachable Points Gracefully
Find the waypoints that cannot be reached before the robot moves. Then move the robot base, split the task into two setups, or use a robot with a longer reach.
Check Joint Limits After IK
The geometric IK function knows nothing about joint limits. A target inside the ring can still need a joint angle outside [theta_min, theta_max]. Follow every IK call with a limit check:
for (t1, t2) in solutions: if (theta1_min <= t1 <= theta1_max and theta2_min <= t2 <= theta2_max): chosen = (t1, t2) # use this solutionIf no solution passes, the real robot cannot reach the target.
Be Consistent About Units
The programs here use millimeters and radians. Two mistakes are common: degrees given to np.cos, and millimeters given to a function that expects meters. Choose one set of units and convert only where the program meets the operator or the hardware.
Next lesson: Orientation and Quaternions describes which way the tool points in 3D.
A welding arm has two links, 400 mm and 300 mm, and two joints. Its torch must touch a point 540 mm from the base. How many different pairs of joint angles put the torch on that point?
The arm is the welding arm: link 1 is 400 mm and link 2 is 300 mm. The shaded ring is its reach, from 100 mm to 700 mm. The elbow-up pose has θ₂ below zero and the elbow-down pose has θ₂ above zero. For each target the angles are solved with the law of cosines, as in the geometric method below. Move the target toward the outer circle: the two elbows come together until the arm is straight and only one solution is left. Outside the ring the grey arm shows the nearest the hand can come.
Three questions. Each wrong choice is a mistake people really make, so read the note after you answer.
1. The welding arm (links 400 mm and 300 mm) must reach the target (600, 0) mm. Which elbow angles θ₂ solve it?
2. The same arm stands at θ₁ = 90° and θ₂ = −90°. Where is the hand?
3. A cable limits the elbow joint of the welding arm to angles from 0° to 150°. The target (500, 200) mm is well inside the ring. How many solutions can the robot use?
No comments yet. Questions, results from your own build, a better way to explain it: all welcome.
Kept on this device only. Nothing is sent anywhere.
Tip: select words in the lesson, or tap a figure or an equation, to put a note right there.
The lesson has changed and these words are no longer in it. Your notes are kept, with the words you chose.
Comments