The hands-on course for robot arms: write the forward kinematics, a DH engine for any robot, the exact and the numerical inverse kinematics, smooth trajectories, then drive a real 3-servo arm with an Arduino. Every program is given in full and was run to produce the outputs shown. It ends with a written exam and five labs.
Before you start
You need basic Python (variables, functions, loops) and the ideas of the maths course: trigonometry, matrices, frames, DH. Each lesson gives a complete file: type it (do not only copy it), run it, compare with the output shown, then change something and predict the result before running again.
Lessons 1 to 4: software only, on any computer.
Lesson 5: a real arm, about 40 € of parts (3 servos, an Arduino, a power supply).
Lesson 6: the exam and the labs that prove you can do it.
1
Your workbench and a first arm in code
15 min
You will learn
to set up Python and NumPy, and to write the forward kinematics of a 2-axis arm as a function you can test.
1.1 Why code it yourself
The other courses explained the formulas. Here you make them run. Writing the code forces you to understand every sign and every angle, and the computer tells you at once if you are wrong. At the end of this course you will have a small library that moves a real arm.
1.2 Install
Python 3 (python.org, or already on Linux and macOS) and the library NumPy: pip install numpy. Optional: matplotlib to draw the arm.
An editor: VS Code, Thonny (very simple for beginners) or any other. Or nothing to install: a Jupyter notebook online such as Google Colab.
Put every file of this course in the same folder: the later lessons import the earlier ones.
1.3 Three NumPy habits
To…
Write
Remember
make a vector
np.array([0.5, 0.2])
vectors add and scale element by element
convert angles
np.radians(30), np.degrees(q)
NumPy works in radians, like all formulas
multiply matrices
A @ B
A * B multiplies element by element: not a matrix product
1.4 Forward kinematics of the 2-axis arm
File arm_fk2.py. The formulas are those of the maths course: the tool is the sum of the arrows of the two links.
"""Forward kinematics of a planar 2-axis arm: from the joint angles to the tool."""
import numpy as np
L1, L2 = 0.5, 0.4 # link lengths (m)
def fk(theta1, theta2):
"""Joint angles (rad) -> positions of the elbow and of the tool (m)."""
elbow = np.array([L1 * np.cos(theta1), L1 * np.sin(theta1)])
tool = elbow + np.array([L2 * np.cos(theta1 + theta2), L2 * np.sin(theta1 + theta2)])
return elbow, tool
if __name__ == '__main__':
for deg in [(0, 0), (30, 45), (90, -90), (120, 60)]:
q = np.radians(deg)
elbow, tool = fk(*q)
print(f'theta = {deg} deg -> elbow ({elbow[0]:6.3f}, {elbow[1]:6.3f}) '
f'tool ({tool[0]:6.3f}, {tool[1]:6.3f}) reach {np.linalg.norm(tool):.3f} m')
(0°, 0°): the arm is stretched along x, the tool must be at L1 + L2 = 0.9 m.
(90°, −90°): link 1 points up, link 2 points right: tool at (0.4, 0.5).
(30°, 45°): the value computed by hand in the maths course, (0.537, 0.636).
If one of these is wrong, the bug is in the code, not in the robot. This habit of “known poses” will save you hours on a real arm.
Key terms
NumPy
function
radians
matrix product @
test pose
The essentials
NumPy works in radians: np.radians() and np.degrees() convert. A @ B is a matrix product.
The tool of a 2-axis arm is the sum of the arrows of the two links.
Test the code with poses you can check by eye before anything else.
The tool of a 2-axis arm is the sum of two arrows: x = L₁ cos θ₁ + L₂ cos(θ₁ + θ₂), y = L₁ sin θ₁ + L₂ sin(θ₁ + θ₂).
Worked exercises
Do each exercise on paper first, then type your answer (a small error is accepted) or pick an option. Open the hint if you are stuck, then read the solution: every step is explained.
Level 1 · Beginner1
np.radians(180) gives?
Solution
π ≈ 3.1416.
Level 2 · Intermediate2
fk(θ1 = 90°, θ2 = 90°) with L1 = 0.5, L2 = 0.4. x of the tool (m)?
Solution
Link 1 up to (0, 0.5), link 2 at 180°: (−0.4, 0). Tool (−0.4, 0.5).
Level 3 · Professional3
Your fk returns (0.9, 0) for (90°, 0°). Most likely bug?
The angles were not converted to radians
cos and sin are swapped, or the angle is ignored
L1 and L2 are swapped
Solution
The right answer is (0, 0.9). Getting (0.9, 0) means the code behaves as if θ1 = 0: cos and sin swapped, or the angle not used. (In degrees by mistake, cos(90 rad) would give an odd value, not exactly 0.9.)
Check yourself
In NumPy, which operator multiplies two matrices?
@ (A @ B). The * operator multiplies element by element.
Why test the pose (0°, 0°) first?
The answer is obvious (the arm is stretched, reach L1 + L2): any other result shows a bug at once.
Does np.cos(90) give 0?
No: 90 is read as radians. Write np.cos(np.radians(90)).
to write one function that computes the pose of the tool of any serial arm from its DH table, in both conventions, and to check that they agree.
Drawing and adding arrows works for 2 joints, not for 6. The DH table (maths course, lessons 6 to 8) turns every robot into a list of rows; the code only needs the matrix of one row and a loop that multiplies them.
"""Forward kinematics of ANY serial arm from its DH table (standard or modified)."""
import numpy as np
def dh_std(theta, d, a, alpha):
"""Standard DH: Rot(z, theta) Trans(z, d) Trans(x, a) Rot(x, alpha)."""
ct, st, ca, sa = np.cos(theta), np.sin(theta), 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 dh_mod(alpha, a, theta, d):
"""Modified DH (DHM): Rot(x, alpha) Trans(x, a) Rot(z, theta) Trans(z, d)."""
ct, st, ca, sa = np.cos(theta), np.sin(theta), np.cos(alpha), np.sin(alpha)
return np.array([[ct, -st, 0, a],
[st * ca, ct * ca, -sa, -d * sa],
[st * sa, ct * sa, ca, d * ca],
[0, 0, 0, 1]])
def fk(rows, joint, q):
"""rows: the DH table; joint(row, qi) -> the matrix of one row. Returns the 4x4 pose of the tool."""
T = np.eye(4)
for row, qi in zip(rows, q):
T = T @ joint(row, qi)
return T
# the 3-axis arm of the course: shoulder height 0.40 m, links 0.45 m and 0.38 m
STD = [(0.40, 0.00, np.pi / 2), (0.0, 0.45, 0.0), (0.0, 0.38, 0.0)] # (d, a, alpha), theta = q
MOD = [(0.0, 0.00, 0.40), (np.pi / 2, 0.00, 0.0), (0.0, 0.45, 0.0), (0.0, 0.38, 0.0)] # (alpha, a, d), theta = q (0 for the tool)
std_joint = lambda row, qi: dh_std(qi, row[0], row[1], row[2])
mod_joint = lambda row, qi: dh_mod(row[0], row[1], qi, row[2])
if __name__ == '__main__':
q = np.radians([25, 70, -80])
T_std = fk(STD, std_joint, q)
T_mod = fk(MOD, mod_joint, list(q) + [0.0]) # the fixed tool row has theta = 0
np.set_printoptions(precision=3, suppress=True)
print('tool position, standard DH :', T_std[:3, 3])
print('tool position, modified DH :', T_mod[:3, 3])
print('same pose (position and orientation):', np.allclose(T_std, T_mod))
print('zero pose (all angles 0) :', fk(STD, std_joint, [0, 0, 0])[:3, 3])
tool position, standard DH : [0.479 0.223 0.757]
tool position, modified DH : [0.479 0.223 0.757]
same pose (position and orientation): True
zero pose (all angles 0) : [0.83 0. 0.4 ]
2.1 Read the code
dh_std and dh_mod are the two matrices of the maths course, written cell by cell. The order of their arguments follows the order of the columns of each table.
fk starts from the identity and multiplies the rows from the base to the tool: T = T1T2 … Tn.
The last column of T (T[:3, 3]) is the position of the tool; the top-left 3×3 block is its orientation.
The robot is only data: to study another robot, change the table, not the code.
What the output proves
The standard and the modified tables of the same arm give the same tool position (0.479, 0.223, 0.757) — the value found by hand in the maths course — and np.allclose confirms that even the orientation is identical. The zero pose gives (0.83, 0, 0.40): the arm stretched along x at the height of the shoulder.
The two classic bugs
Feeding a standard table to the modified matrix (or the reverse): no error, just a wrong robot. Keep the convention in the name of the function.
Degrees instead of radians in α: write np.pi / 2 or np.radians(90), never 90.
Key terms
DH table
homogeneous matrix
loop
np.allclose
The essentials
One function per row (dh_std or dh_mod), one loop that multiplies the rows.
The robot is data: change the table, not the code.
Check: both conventions give the same pose; the zero pose matches the drawing.
The DH engine: the robot is a table of numbers; one function turns each row into a matrix, one loop multiplies them.
Worked exercises
Do each exercise on paper first, then type your answer (a small error is accepted) or pick an option. Open the hint if you are stuck, then read the solution: every step is explained.
Level 1 · Beginner1
A 6-axis robot in standard DH: how many rows in the table?
Solution
One per joint: 6.
Level 2 · Intermediate2
dh_std(θ = 0, d = 0.2, a = 0.3, α = 0): x of the translation (last column)?
Solution
a cos θ = 0.3 × 1 = 0.3 (and z = d = 0.2).
Level 3 · Professional3
3-axis arm of the lesson, θ = (0°, 90°, 0°). z of the tool (m)?
Solution
Both links point straight up: 0.40 + 0.45 + 0.38 = 1.23 m.
Check yourself
Where do you read the position of the tool in the 4×4 matrix T?
In the last column, first three rows: T[:3, 3].
To study a SCARA instead of the 3-axis arm, what do you change?
Only the DH table (the data); the functions stay the same.
Why does the modified table have one more row?
Its last frame sits on the last joint; a fixed row (θ = 0) brings it to the tool.
to code the exact inverse kinematics of the 2-axis arm with its two elbow solutions, to detect unreachable points, and to test it with the round trip FK(IK(x)) = x.
3.1 The formulas
The distance from the base to the target fixes the angle of the elbow (law of cosines); then the direction of the target fixes the shoulder:
cos θ2 = (x² + y² − L1² − L2²) / (2 L1L2) θ1 = atan2(y, x) − atan2(L2 sin θ2, L1 + L2 cos θ2)
If |cos θ2| > 1 the point is out of reach: return “no solution” instead of crashing.
sin θ2 = ±√(1 − cos² θ2): the two signs are the two elbows (up and down).
Use atan2, never arccos alone or arctan of a ratio: they lose the quadrant.
"""Closed-form inverse kinematics of the planar 2-axis arm, with both elbow solutions."""
import numpy as np
from arm_fk2 import fk, L1, L2
def ik(x, y, elbow_up=True):
"""Tool position (m) -> joint angles (rad), or None if the point is out of reach."""
c2 = (x * x + y * y - L1 * L1 - L2 * L2) / (2 * L1 * L2) # law of cosines
if abs(c2) > 1:
return None # too far or too close
s2 = np.sqrt(1 - c2 * c2) * (-1 if elbow_up else 1) # the two signs = the two elbows
theta2 = np.arctan2(s2, c2)
theta1 = np.arctan2(y, x) - np.arctan2(L2 * s2, L1 + L2 * c2)
return theta1, theta2
if __name__ == '__main__':
for target in [(0.537, 0.636), (0.6, 0.2), (1.0, 0.0)]:
print('target', target)
for up in (True, False):
sol = ik(*target, elbow_up=up)
if sol is None:
print(' out of reach (max reach 0.9 m)')
break
_, tool = fk(*sol) # round trip: FK(IK(x)) must give x back
print(f' elbow {"up " if up else "down"}: theta = ({np.degrees(sol[0]):7.2f}, {np.degrees(sol[1]):7.2f}) deg'
f' check FK -> ({tool[0]:.3f}, {tool[1]:.3f})')
target (0.537, 0.636)
elbow up : theta = ( 69.69, -45.00) deg check FK -> (0.537, 0.636)
elbow down: theta = ( 29.96, 45.00) deg check FK -> (0.537, 0.636)
target (0.6, 0.2)
elbow up : theta = ( 57.65, -91.43) deg check FK -> (0.600, 0.200)
elbow down: theta = ( -20.78, 91.43) deg check FK -> (0.600, 0.200)
target (1.0, 0.0)
out of reach (max reach 0.9 m)
3.2 The round trip test
The best test of an inverse model needs no answer key: compute the forward kinematics of the solution and compare with the target. Here both elbows give back (0.537, 0.636) exactly, and the elbow-down solution (29.96°, 45°) is, with rounding, the pose (30°, 45°) of lesson 1. The point at 1.0 m is correctly refused: the reach is 0.9 m.
Which elbow to choose?
A real controller keeps the solution closest to the current pose (smallest joint motion), and checks the joint limits and the obstacles. Switching elbow in the middle of a motion makes the arm flip: never do it while moving.
Key terms
inverse kinematics
closed form
law of cosines
elbow up / down
round trip test
The essentials
cos θ2 from the law of cosines; |cos θ2| > 1 means out of reach.
Two solutions: sin θ2 = ±√(1 − cos² θ2), elbow up or down. Always use atan2.
Round trip test: fk(ik(x)) must give x back.
The same target, two answers: the sign of sin θ₂ chooses the elbow up or the elbow down.
Worked exercises
Do each exercise on paper first, then type your answer (a small error is accepted) or pick an option. Open the hint if you are stuck, then read the solution: every step is explained.
Level 1 · Beginner1
Target (0.9, 0) for L1 = 0.5, L2 = 0.4. cos θ2?
Solution
(0.81 − 0.25 − 0.16) / 0.4 = 0.4 / 0.4 = 1: θ2 = 0, the arm is stretched (one solution only).
Level 2 · Intermediate2
Smallest distance from the base that the tool can reach (m)?
Solution
Folded arm: |L1 − L2| = 0.5 − 0.4 = 0.1 m. The workspace is a ring from 0.1 m to 0.9 m.
Level 3 · Professional3
Target (0, 0.64). Compute |θ2| in degrees.
Solution
cos θ2 = (0.4096 − 0.25 − 0.16) / 0.4 = −0.001, so |θ2| = 90.06°: almost a right angle, like the pose (90°, −90°) of lesson 1.
Check yourself
What does |cos θ₂| > 1 mean?
The target is out of reach (too far or too close): there is no solution.
How do you test an inverse model without knowing the right angles?
Apply the forward model to the solution and check that it gives back the target.
Where do the two solutions of the 2-axis arm come from?
From the sign of sin θ₂ = ±√(1 − cos² θ₂): elbow up or elbow down.
4
The Jacobian and numerical inverse kinematics
18 min
You will learn
to compute the Jacobian of any arm with finite differences, and to solve the inverse kinematics of any arm step by step, safely near singularities.
A closed-form inverse model exists only for simple robots. For any other one, the computer searches: from a guess, it moves the joints a little in the direction that brings the tool closer, again and again. It is exactly what the “Build your first robot” workshop does when you press “Send the tool to the ball”.
4.1 The Jacobian by finite differences
Column i of the Jacobian is “how the tool moves when joint i turns a little” (maths course, lesson 9). No need to derive anything: turn joint i by a tiny h, measure how much the tool moved, divide by h. It works for any robot that has a forward model.
4.2 The search: damped least squares
At each step: error e = target − position; correction Δq = JT (J JT + λ² I)−1e; new q = q + Δq, kept inside the joint limits. The small λ (the damping) keeps the step small near a singularity, where J JT can no longer be inverted (singularities course, lesson 8).
"""Numerical inverse kinematics for any arm: Jacobian by finite differences + damped least squares."""
import numpy as np
from arm_dh import fk, STD, std_joint
LIMITS = np.radians([[-170, 170], [-10, 170], [-150, 150]])
def position(q):
return fk(STD, std_joint, q)[:3, 3]
def jacobian(q, h=1e-6):
"""3 x n matrix: column i = how the tool moves when joint i turns a little."""
p0 = position(q)
J = np.zeros((3, len(q)))
for i in range(len(q)):
dq = np.array(q, dtype=float)
dq[i] += h
J[:, i] = (position(dq) - p0) / h
return J
def ik(target, q0, damping=0.01, tol=1e-4, max_iter=100):
q = np.array(q0, dtype=float)
for it in range(max_iter):
error = target - position(q)
if np.linalg.norm(error) < tol:
return q, it
J = jacobian(q)
# damped least squares: dq = J^T (J J^T + lambda^2 I)^-1 error (safe near singularities)
dq = J.T @ np.linalg.solve(J @ J.T + damping ** 2 * np.eye(3), error)
q = np.clip(q + dq, LIMITS[:, 0], LIMITS[:, 1])
return q, max_iter
if __name__ == '__main__':
np.set_printoptions(precision=3, suppress=True)
target = np.array([0.479, 0.223, 0.757]) # the tool position of the DH lesson
q, n = ik(target, q0=np.radians([0, 45, -45]))
print(f'converged in {n} iterations: q = {np.degrees(q)} deg')
print('reached position:', position(q), ' error (mm):', round(1000 * np.linalg.norm(position(q) - target), 3))
# 20 random reachable targets: pick random joint angles, compute the position, then solve back
rng = np.random.default_rng(1)
targets = [position(rng.uniform(LIMITS[:, 0] * 0.8, LIMITS[:, 1] * 0.8)) for _ in range(20)]
ok1 = ok2 = 0
for p in targets:
q_sol, _ = ik(p, q0=np.radians([0, 45, -45])) # always the same start
ok1 += np.linalg.norm(position(q_sol) - p) < 1e-3
for start in [np.radians([0, 45, -45])] + [rng.uniform(LIMITS[:, 0], LIMITS[:, 1]) for _ in range(5)]:
q_sol, _ = ik(p, q0=start) # retry from other starts if needed
if np.linalg.norm(position(q_sol) - p) < 1e-3:
ok2 += 1
break
print(f'random targets reached within 1 mm, one start : {ok1} / 20')
print(f'random targets reached within 1 mm, up to 6 starts: {ok2} / 20')
converged in 4 iterations: q = [ 24.965 69.974 -79.944] deg
reached position: [0.479 0.223 0.757] error (mm): 0.003
random targets reached within 1 mm, one start : 12 / 20
random targets reached within 1 mm, up to 6 starts: 20 / 20
4.3 What the output teaches
For the target of lesson 2 the search finds (25°, 70°, −80°) in 4 iterations, with an error of 0.003 mm: the angles that created this point.
From one fixed start it reaches only 12 targets out of 20: a local search can get stuck against a joint limit, or go towards the other elbow and stop.
With up to 6 starts it reaches 20 out of 20. Real solvers do the same: they restart from other guesses, and start from the current pose of the robot, which is usually close to the answer.
Always check the result
A numerical solver can return angles that do not reach the target. Never send its answer to the motors without checking the error with the forward model, as the code does with np.linalg.norm(position(q_sol) - p).
Key terms
Jacobian
finite difference
damped least squares
local minimum
restart
The essentials
Jacobian by finite differences: turn joint i by h, measure the motion of the tool, divide by h.
Damped least squares: Δq = Jᵀ (J Jᵀ + λ² I)⁻¹ e, repeated until the error is small.
A local search can fail: restart from other guesses and always check the error.
Numerical inverse kinematics: each step Δq = Jᵀ (J Jᵀ + λ² I)⁻¹ e reduces the error, but a poor starting guess can get stuck: always check the final error.
Worked exercises
Do each exercise on paper first, then type your answer (a small error is accepted) or pick an option. Open the hint if you are stuck, then read the solution: every step is explained.
Level 1 · Beginner1
A 3-axis arm with a 3D tool position: size of its Jacobian (number of entries)?
Solution
3 rows (x, y, z) × 3 columns (joints) = 9.
Level 2 · Intermediate2
h = 10⁻⁶ rad moves the tool by 4.5 × 10⁻⁷ m in z. Entry ∂z/∂q (m/rad)?
Solution
4.5 × 10⁻⁷ / 10⁻⁶ = 0.45 m/rad: the length of the link that this joint lifts.
Level 3 · Professional3
12 of 20 targets reached from one start, 20 of 20 with up to 6 starts. Share of the targets saved by the restarts (%)?
Solution
8 / 20 = 40 %. Never trust a single start.
Check yourself
How is column i of the Jacobian computed numerically?
Turn joint i by a tiny h, measure how the tool moves, divide by h.
What is the damping λ for?
To keep the steps small and finite near a singularity, where J Jᵀ cannot be inverted.
The solver reaches only 12 targets out of 20 from one start. What do you do?
Restart from other guesses (and from the current pose), and keep the solution whose error is below the tolerance.
From the code to a real arm: trajectories and servos
22 min
You will learn
to generate a smooth motion, to turn angles into servo pulses, and to build and drive a small 3-servo arm with an Arduino.
5.1 A smooth motion: the degree-5 polynomial
Jumping from one angle to another shakes the arm. The quintic law (modelling course, lesson 9) goes from q0 to q1 in a time T with zero speed and zero acceleration at both ends. Its peak speed, at mid-time, is 1.875 times the average speed: use it to check that the servos are fast enough.
"""A smooth joint trajectory (degree-5 polynomial) and the servo pulses that follow it."""
import numpy as np
def quintic(q0, q1, T, t):
"""Position at time t of a motion from q0 to q1 in T seconds, with zero speed and acceleration at both ends."""
s = np.clip(t / T, 0.0, 1.0)
return q0 + (q1 - q0) * (10 * s**3 - 15 * s**4 + 6 * s**5)
def to_pulse_us(angle_deg, offset_deg=0.0, us_min=500, us_max=2500):
"""Hobby servo: 0..180 deg -> 500..2500 microseconds; offset_deg = calibration of the zero."""
a = np.clip(angle_deg + offset_deg, 0, 180)
return int(round(us_min + (us_max - us_min) * a / 180))
if __name__ == '__main__':
q_start = np.array([90.0, 45.0, 120.0]) # servo angles (deg)
q_goal = np.array([30.0, 100.0, 60.0])
T = 2.0 # duration (s)
offsets = [0.0, -3.0, 2.0] # measured once, servo by servo
for t in np.arange(0.0, T + 1e-9, 0.5):
q = quintic(q_start, q_goal, T, t)
pulses = [to_pulse_us(a, o) for a, o in zip(q, offsets)]
print(f't = {t:.1f} s angles = {np.round(q, 1)} deg pulses = {pulses} us')
mid_speed = (quintic(q_start, q_goal, T, 1.001) - quintic(q_start, q_goal, T, 0.999)) / 0.002
print('peak speed at mid-time (deg/s):', np.round(mid_speed, 1), ' = 1.875 x average speed')
t = 0.0 s angles = [ 90. 45. 120.] deg pulses = [1500, 967, 1856] us
t = 0.5 s angles = [ 83.8 50.7 113.8] deg pulses = [1431, 1030, 1787] us
t = 1.0 s angles = [60. 72.5 90. ] deg pulses = [1167, 1272, 1522] us
t = 1.5 s angles = [36.2 94.3 66.2] deg pulses = [902, 1515, 1258] us
t = 2.0 s angles = [ 30. 100. 60.] deg pulses = [833, 1578, 1189] us
peak speed at mid-time (deg/s): [-56.2 51.6 -56.2] = 1.875 x average speed
5.2 Servos: angle → pulse
A hobby servo receives a pulse every 20 ms; its width sets the angle: typically 500 µs → 0°, 1500 µs → 90°, 2500 µs → 180° (check the data sheet: many use 1000 to 2000 µs).
The servo contains its own motor, gearbox, potentiometer and P controller: you only send the target angle.
Each servo is mounted a little off: measure its offset once (send 90°, measure the real angle) and add it in software.
Joint angle and servo angle differ: usually servo = 90° + θ (or 90° − θ if it is mounted the other way). Write this mapping in one function, and test it joint by joint.
A hobby servo receives one pulse every 20 ms; only the width of the pulse matters: about 0.5 ms for 0°, 1.5 ms for 90°, 2.5 ms for 180°.
5.3 Build the arm
Part
Example
Note
3 servos
MG996R (metal gears) for the base and the shoulder; SG90 for a very small arm
the shoulder carries the most torque (control course, lesson 1)
Microcontroller
Arduino Uno or Nano
or a PCA9685 board to drive up to 16 servos
Power supply
5 to 6 V, at least 3 A
never power the servos from the 5 V pin of the Arduino; connect the grounds together
Links
3D-printed, laser-cut, or thick cardboard and servo horns
measure L1, L2 between the servo axes and put them in the code
Tool
a pen holder
drawing makes the errors visible
5.4 The code on both sides
The Arduino only receives three angles per line and moves the servos. All the maths (trajectory, inverse kinematics, offsets) stays in Python on the computer, where it is easy to debug.
// Arduino sketch: receives "a1 a2 a3" (servo angles in degrees, one line per command) and moves 3 servos.
#include <Servo.h>
Servo s[3];
const int PINS[3] = {9, 10, 11};
void setup() {
Serial.begin(115200);
for (int i = 0; i < 3; i++) {
s[i].attach(PINS[i], 500, 2500); // pulse range in microseconds (check your servo's data sheet)
s[i].write(90); // start in the middle
}
}
void loop() {
if (Serial.available()) {
for (int i = 0; i < 3; i++) {
int a = Serial.parseInt(); // reads the next integer of the line
s[i].write(constrain(a, 0, 180)); // never send a servo beyond its range
}
while (Serial.available() && Serial.read() != '\n') {} // drop the end of the line
}
}
"""Send a smooth trajectory to the 3-servo arm over USB (pip install pyserial numpy)."""
import time
import numpy as np
import serial # pyserial
from arm_traj import quintic
PORT = '/dev/ttyACM0' # Windows: 'COM3'; macOS: '/dev/cu.usbmodem...'
OFFSETS = np.array([0.0, -3.0, 2.0]) # calibration of each servo (deg)
with serial.Serial(PORT, 115200, timeout=1) as link:
time.sleep(2) # the Arduino restarts when the port opens
q_start, q_goal, T, dt = np.array([90, 45, 120.0]), np.array([30, 100, 60.0]), 2.0, 0.02
t0 = time.time()
while (t := time.time() - t0) <= T:
q = np.clip(quintic(q_start, q_goal, T, t) + OFFSETS, 0, 180)
link.write(('%d %d %d\n' % tuple(np.round(q))).encode())
time.sleep(dt) # 50 commands per second
Before powering the arm
These two programs were written for this course but could not be tested on hardware here. Read the error messages, and test step by step: one servo, then the three, then a slow trajectory.
Servos jump to their position at power-up: keep your fingers away and start with the arm in its middle pose.
Keep a hand on the power switch: it is your emergency stop.
Draw a square
Choose 4 corners of a 6 cm square in front of the robot, on the paper.
Cut each side into 20 points; compute the inverse kinematics of each point (lesson 3 or 4).
Send the angles at a steady rhythm. Measure the drawn square: the error shows your offsets and link lengths. Correct them and draw again.
Key terms
quintic trajectory
servo
pulse width
offset calibration
serial link
The essentials
Quintic law: zero speed and acceleration at both ends; peak speed = 1.875 × average.
Servo: the pulse width sets the angle (about 500–2500 µs for 0–180°); measure each offset once.
Separate power for the servos, common ground, maths in Python, the Arduino only moves the servos.
The quintic law: it starts and stops with zero speed and acceleration, so the servos move smoothly; its peak speed is 1.875 times the average.
Worked exercises
Do each exercise on paper first, then type your answer (a small error is accepted) or pick an option. Open the hint if you are stuck, then read the solution: every step is explained.
Level 1 · Beginner1
Pulse for 90° on a 500–2500 µs servo (µs)?
Solution
500 + 2000 × 90/180 = 1500 µs: the middle.
Level 2 · Intermediate2
A servo turns at 300 °/s at most. A quintic motion of 90°: shortest duration T (s)?
Hint
Peak speed = 1.875 × 90 / T ≤ 300.
Solution
T ≥ 1.875 × 90 / 300 = 0.5625 s.
Level 3 · Professional3
Three servos draw up to 1.2 A each at 6 V. Minimum power of the supply (W)?
Solution
3 × 1.2 = 3.6 A; 3.6 × 6 = 21.6 W. Take a margin: 5 A or more.
Check yourself
Why is a servo arm moved along a quintic trajectory instead of jumping to the target?
It starts and stops with zero speed and acceleration: no shock, no shaking.
Why must the servos have their own power supply?
They draw peaks of several amperes; the Arduino 5 V pin cannot give them and the board would reset or break.
Why keep the maths in Python and not in the Arduino?
It is easier to write, test and debug on the computer; the Arduino only needs to move the servos.
6
Final exam and labs: prove it
60 min
You will learn
to check that you can compute, code and build: a written exam and five labs.
The course is complete when you pass the written exam (70 % or more) and do at least 4 of the 5 labs. Your progress is kept in this browser.
Written exam
Each question is checked once: your first answer counts. The solution appears below it to learn from your mistakes.
Level 1 · Beginner1
2-axis arm, L1 = 0.5 m, L2 = 0.4 m, θ = (90°, 0°). y of the tool (m)?
Solution
Both links point up: y = 0.5 + 0.4 = 0.9 m.
Level 1 · Beginner2
Same arm, θ = (0°, 90°). y of the tool (m)?
Solution
Link 1 along x, link 2 up: tool at (0.5, 0.4).
Level 1 · Beginner3
How many inverse kinematics solutions does the 2-axis arm have for a point strictly inside its workspace?
Solution
2: elbow up and elbow down (one only on the boundary, when the arm is stretched or folded).
Level 1 · Beginner4
A table has the columns α, a, θ, d. Which convention?
Modified DH (DHM)
Standard DH
Solution
The moves along x come first: modified DH.
Level 1 · Beginner5
The 3-axis arm of the course (d1 = 0.40, a2 = 0.45, a3 = 0.38), all angles at 0. x of the tool (m)?
Solution
Stretched along x: 0.45 + 0.38 = 0.83 m (at the height 0.40 m).
Level 2 · Intermediate6
2-axis arm (0.5 m, 0.4 m), target (0.6, 0.2). |θ2| in degrees?
Hint
cos θ2 = (x² + y² − L1² − L2²) / (2 L1 L2).
Solution
cos θ2 = (0.36 + 0.04 − 0.25 − 0.16) / 0.4 = −0.025, so |θ2| = 91.43° (the output of lesson 3).
Level 2 · Intermediate7
Is the point (0.7, 0.6) reachable by the 2-axis arm (0.5 m, 0.4 m)?
No: it is 0.92 m away, the reach is 0.9 m
Yes, with the elbow up
Yes, with the elbow down
Solution
√(0.49 + 0.36) = 0.922 m > 0.9 m: out of reach; cos θ2 would be greater than 1.
Level 2 · Intermediate8
det J of the 2-axis arm is L1 L2 sin θ2. Value at θ2 = 30° (m²)?
Solution
0.5 × 0.4 × 0.5 = 0.1 m². It is 0 at θ2 = 0: the stretched arm is singular.
Level 2 · Intermediate9
Turning joint 2 by 0.001 rad moves the tool by 0.25 mm. Value of this entry of the Jacobian (m/rad)?
Solution
0.00025 m / 0.001 rad = 0.25 m/rad: the finite difference of lesson 4.
Level 2 · Intermediate10
Why add a damping λ in the numerical inverse kinematics?
To avoid huge steps near a singularity
To go faster far from singularities
To respect the joint limits
Solution
Near a singularity J Jᵀ is almost not invertible: without λ the correction explodes. The limits are handled by the clipping.
Level 3 · Professional11
A quintic motion of 60° in 2 s. Peak speed (°/s)?
Solution
Average 30 °/s × 1.875 = 56.25 °/s, reached at mid-time.
Level 3 · Professional12
A servo maps 0–180° to 500–2500 µs. Pulse for 45° (µs)?
Solution
500 + 2000 × 45 / 180 = 500 + 500 = 1000 µs.
The five labs
Lab 1 — Forward kinematics
Run arm_fk2.py and reproduce its output. Change L2 to 0.3 m and predict, then check, the new reach at (0°, 0°). Pass: your prediction matches the program.
Lab 2 — A DH table of your own
Write the standard and the modified DH tables of the SCARA of the workshop (two horizontal links of 0.42 m and 0.32 m, a vertical slider). Put them in arm_dh.py. Pass: both tables give the same tool pose for 3 different poses.
Lab 3 — The round trip
Draw 100 random points in a square of 2 m around the base. For each, compute ik then fk. Pass: every reachable point comes back within 10⁻⁹ m, and you can explain how many were refused and why.
Lab 4 — Numerical IK
Reproduce the 20 / 20 of lesson 4, then remove the damping (λ = 0) and try targets close to the stretched arm. Pass: you can show and explain what goes wrong without damping.
Lab 5 — The real arm
Build the 3-servo arm of lesson 5, calibrate the offsets, and draw a 6 cm square. Pass: every side is 6 cm ± 5 mm.
Key terms
exam
lab
pass criterion
Check yourself
What do you need to complete the course?
At least 70 % at the written exam and at least 4 of the 5 labs.
Glossary
All the words of the course in one place.
Term
Meaning
Forward kinematics (FK, MGD)
From the joint angles to the pose of the tool.
Inverse kinematics (IK, MGI)
From the wanted pose of the tool to the joint angles.
Round trip test
Checking an inverse model by applying the forward model to its answer.
Finite difference
A derivative estimated as (change of output) / (small change of input).
Damped least squares
A numerical IK step that stays small near singularities.
Quintic trajectory
A degree-5 polynomial motion with zero speed and acceleration at both ends.
Servo offset
The angle error of a mounted servo, measured once and corrected in software.
Sources and references
This course was written from these books, papers, standards and documentation. They are also the best way to go further.
J. J. Craig, Introduction to Robotics: Mechanics and Control, 4th ed., Pearson, 2017.used for:forward and inverse kinematics, DH
K. M. Lynch, F. C. Park, Modern Robotics: Mechanics, Planning, and Control, Cambridge University Press, 2017 (free at modernrobotics.org).used for:numerical inverse kinematics
C. W. Wampler, “Manipulator inverse kinematic solutions based on vector formulations and damped least-squares methods”, IEEE Transactions on Systems, Man, and Cybernetics, 16(1), 1986.used for:damped least squares
W. Khalil, E. Dombre, Modeling, Identification and Control of Robots, Hermes Penton Science, 2002 (French edition: Modélisation, identification et commande des robots, Hermès, 1999).used for:polynomial motion laws