Skip to content
You Start with one site
Amounts in Start with one site
Mechanical Engineering & Design · Course

Forward and Inverse Kinematics

Lesson 2 of 6 17 min read
Found this useful?

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

Learning Objectives

By the end of this lesson, you will be able to:

  1. Derive forward kinematics equations for planar 2R and 3R robot arms using trigonometry and transformation matrices
  2. Apply Denavit-Hartenberg (DH) parameter conventions to systematically build FK solutions for serial manipulators
  3. Solve inverse kinematics using geometric (closed-form) methods for 2R planar robots
  4. Identify multiple IK solutions (elbow-up vs. elbow-down) and select the appropriate configuration for a given task
  5. Implement numerical IK using Jacobian-based Newton-Raphson iteration for robots without closed-form solutions
  6. Analyze workspace boundaries, singularities, and unreachable positions

Real-World Engineering Challenge: Robotic Welding of Curved Seams



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 mm and mm. The seam is an arc, given as a row of points called waypoints, and the torch must be within about a millimetre of each one. The far part of the seam comes within about 120 mm of the edge of the region the arm can reach.

Why This Problem Matters in Industry

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.

Forward Kinematics: From Joint Angles to End-Effector Position



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.

FK for a 2R Planar Robot

2R planar arm: the two joint angleshand (x_e, y_e)link 2, length L2elbowo.....link 1 continued(x1, y1)theta2 = turn of link 2awayfromthislinelink 1, length L1theta1base (0,0)ox

Link 1 has length and points at the angle , measured counterclockwise from the axis. Link 2 has length . Its angle is measured from the direction of link 1, counterclockwise positive, so link 2 points at in the plane.

Walk from the base to the hand. A link of length that points at an angle moves you along and along . After link 1 you are at the elbow:

Add link 2 to reach the end-effector:

Every pair gives exactly one position.

Worked example. Take and . Link 2 points at .

The elbow is at (282.8, 282.8) mm and the torch is at (572.6, 360.5) mm ✅

FK Implementation in Python

The program repeats the worked example and prints the same two positions.

import numpy as np
import 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 = 300mm
L1, L2 = 400, 300
theta1 = np.radians(45) # 45 degrees
theta2 = 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")

Visualizing the Robot Arm Configuration

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}°")

Denavit-Hartenberg (DH) Parameter Convention

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 , and axes) to each link, with along a joint axis. Four numbers then lead from one frame to the next.

Two neighbouring DH framesz_{i-1}z_id_i: slide along z_{i-1}x_{i-1}x_iframe i-1frame i|a_i: slide along x_i|
ParameterSymbolDescription
Joint angleTurn about that brings to (radians)
Link offsetSlide along (mm)
Link lengthSlide along (mm)
Link twistTurn about that brings to (radians)

A revolute joint changes as it moves, and a prismatic (sliding) joint changes . The other numbers are fixed by the way the robot is built.

The four moves, done in the order of the table, are written as one matrix called a homogeneous transformation: its upper left block holds the turn, and its last column holds the shift (see Elementary Matrix Methods and Link Modeling). The matrix from frame to frame is:

Forward kinematics is then one multiplication, in order from the base to the end-effector (ee), for an arm with joints:

The last column of the result holds the position of the end-effector.

In our planar arm all joint axes are parallel, so and . The program below builds the table for the welding arm and prints (572.6, 360.5) mm, the position of the worked example ✅

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 before
q = [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")
DH parameters for common industrial robots

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: From Target Position to Joint Angles



Inverse kinematics is the harder question: from a known target position , find the joint angles that put the end-effector there. Forward kinematics always has exactly one answer. Inverse kinematics can have none, one or several.

Two answers for one target

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:

  • Elbow-up: the elbow is above the line from base to target. Link 2 turns clockwise from link 1, so .
  • Elbow-down: the elbow is below that line. Link 2 turns counterclockwise from link 1, so .
One target, two solutionsElbow-up (theta2 < 0)Elbow-down (theta2 > 0)elbowo* target* targetbase obase oo elbow

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.

Two ways to solve it

The geometric method is an exact formula for simple arms. The numerical method corrects a guess step by step and works for any arm.

Geometric Inverse Kinematics for a 2R Planar Robot

The base, the elbow and the target make a triangle. Two sides are the links, and , and the third is the distance from the base to the target. All three sides are known, so the angles can be found.

Step 1: Solve for using the law of cosines.

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 , and , so the usual minus sign of the law becomes a plus:

Solve for , and call it :

A cosine lies between and . If is outside that range, no triangle exists and the target cannot be reached. Otherwise two angles have this cosine, one positive and one negative:

The positive value is the elbow-down solution and the negative value is the elbow-up solution.

For the target (500, 200) mm with mm and mm:

Step 2: Solve for .

The angle is the direction from the base to the target, minus the angle between link 1 and that direction. Seen from link 1, the hand is along the link and to its side:

Then:

For the target (500, 200) mm, mm and mm:

  • Elbow-down: , . The elbow is at (391.9, -79.9) mm, below the line to the target ✅
  • Elbow-up: , . The elbow is at (228.7, 328.1) mm, above the line ✅

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, 300
target = (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")

Visualizing Multiple IK Solutions

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)

Workspace Analysis



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:

  • The outer circle has radius , the arm stretched straight. For the welding arm, mm.
  • The inner circle has radius , link 2 folded back along link 1. For the welding arm, mm.

If the inner circle shrinks to the base and the whole disk can be reached.

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)

Reachability Check

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 points
L1, L2 = 400, 300
test_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")

System Application: Welding Seam Following



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 (elbow-down, the setting passed to it). Along the seam rises smoothly from to , and stays between and , far from the straight arm.

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 degrees
L1, L2 = 400, 300
waypoints = 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 results
print(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}")

Complete Weld Path Visualization

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)

Design Guidelines



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 to . Typical values of are to .

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 solution

If 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.

Summary



  • Forward kinematics turns joint angles into one end-effector position: add the links, each with the cosine and sine of its direction. For longer arms, a DH table and a product of matrices do the same work.
  • Inverse kinematics turns a target into joint angles. A target inside the ring has two solutions, elbow-up and elbow-down. A target on the edge has one, and a target outside has none.
  • The geometric method is exact and fast, but exists only for simple arms.
  • The numerical method corrects a guess with the Jacobian. It works for any arm and returns one solution.
  • For a path, test every waypoint for reach and keep one elbow configuration.

Next lesson: Orientation and Quaternions describes which way the tool points in 3D.



Comments

Loading comments...
© 2021-2026 SiliconWit®. All rights reserved.
Predict first

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?

See it: move the target and count the solutions

Elbow-up: θ₁, θ₂
Target to base
Elbow-down: θ₁, θ₂

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.

Check yourself

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?

Two answersOne answerNo answer inside the ringon the edge100 mm outside
seam Elbow-down: θ₁ = 0.6°Elbow-up: θ₁ = 59.9° Same torch point.A switch swings the arm 59°. Keep one elbow along the seam.
Watch it build: two joint angles from one target
x r 400 300 up (500, 200) Find θ₁ and θ₂ r = 538.5 mm 99.6° cos θ₂ = 0.1667 down θ₂ −80.41° +80.41° 21.8° 33.3° θ₁ 55.12° −11.52°
  1. Base, elbow and target make a triangle. Two sides are the links, 400 mm and 300 mm.
  2. Pythagoras gives the third side: r = √(500² + 200²) = 538.5 mm.
  3. The law of cosines gives cos θ₂ = 0.1667. The angle inside the triangle at the elbow is 99.6°.
  4. θ₂ = ±80.41°: two triangles, mirror images in the line to the target.
  5. The line to the target points at atan2(200, 500) = 21.80° from the x axis.
  6. Link 1 is 33.32° off that line: θ₁ = 55.12° with the elbow up, −11.52° with the elbow down.
base (0, 0)elbow (x1, y1)hand (xe, ye)x (282.8, 282.8) mm(572.6, 360.5) mm link 1, L1 = 400 mm link 2, L2 = 300 mm θ1 = 45° θ2 = −30° from link 1 continued (dotted)
To scale for the lesson's example: L1 = 400 mm, L2 = 300 mm, θ1 = 45°, θ2 = −30°.
zi−1zixi−1xi frame i−1frame i diai slide along z i−1slide along x i
Here θi = 0 and αi = 0, so only the two slides, di and ai, show.
Found this useful?

Discussion

    Comments show your name. Be kind, stay on the topic.