Python for robotics

← Robot list · The basics

The programming every other course needs, from zero: variables, angles and the math module, loops, functions, lists, NumPy, plots and data files, classes — and, at the end, the loop of a first controller. Every example is about a robot and every program was run: what you see under it is its real output.

How to use this course

No prerequisite: you only need a computer. Type each program yourself rather than copying it, run it, check that you get the same output, then change one value and predict the new result before running it again. Each lesson ends with exercises whose solutions give the rule used and where it is in the lesson.

  • Lessons 1 to 4: the language (types, maths, loops, functions).
  • Lessons 5 to 8: the tools of robotics (lists, NumPy, plots, classes and a controller).
  • Next: the course “Code a robot arm in Python” and ROS 2 from zero.
1

Your first program: variables and types

20 min
You will learn

why robots are programmed in Python, how to install it, how to run a program, and the four basic types of values: whole numbers, decimal numbers, texts and true/false.

In one sentence

A program is a list of instructions run from top to bottom; a variable is a name that holds a value.

1.1 Why Python?

Python is the most used language to prototype robots: it is easy to read, it has ready-made libraries for maths (NumPy), plots (Matplotlib), vision (OpenCV) and robots (ROS 2 speaks Python). The fast loops inside a motor drive are written in C or C++, but almost everything around them — tests, calculations, planning, data — is written in Python.

1.2 Install and run

  1. Install Python 3 from python.org (on Windows, tick “Add Python to PATH”). On Linux and macOS it is often already there.
  2. Install an editor: Thonny (made for beginners) or VS Code with the Python extension.
  3. Write the program below in a file hello.py and run it (the Run button, or python hello.py in a terminal).
  4. Later, add the libraries of this course with pip install numpy matplotlib.

1.3 Variables and types

# my first robot program: variables, types and print
name = "R2"              # a text (str)
joints = 3               # a whole number (int)
length = 0.45            # a decimal number (float), in metres
powered = True           # True or False (bool)

print("Robot", name, "has", joints, "joints")
print("Link length:", length, "m")
print("Powered:", powered)
print(type(joints), type(length))

What it prints:

Robot R2 has 3 joints
Link length: 0.45 m
Powered: True
<class 'int'> <class 'float'>
TypeExampleIn a robot
int3, -90a number of joints, an encoder count
float0.45, -1.5e-3a length, an angle, a speed
str"R2"a name, a message
boolTrue, Falsepowered or not, a limit switch pressed
Three beginner traps
  • Python counts the spaces at the start of a line: they say which lines belong together (lesson 3).
  • The decimal mark is a point: 0.45, never 0,45 (a comma makes two values).
  • = stores a value; == compares two values.

Key terms

  • program
  • variable
  • int, float, str, bool
  • print
  • editor

Exercises

Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.

Level 1 · Beginner1

What is the type of the value True?

  1. int
  2. str
  3. bool
  4. float

Solution

Rule used True and False are the two values of the type bool (true/false) lesson 1 — 1.3 Variables and types (table)

  1. True has no quotes, so it is not a text (str).
  2. It is not a number either: it is one of the two values of a yes/no question.

Answer bool (C)

Level 1 · Beginner2

After n = 6 then n = n + 1, what does print(n) show?

Solution

Rule used = computes the right-hand side first, then stores the result in the name on the left lesson 1 — 1.3, box “Three beginner traps”

  1. n holds 6.
  2. n + 1 is computed with the old value: 6 + 1 = 7.
  3. 7 is stored in n, which replaces 6.

Answer 7

Check yourself
  1. What is the type of 0.45?

    float (a decimal number).

  2. How do you write one and a half in Python?

    1.5 — with a point, not a comma.

  3. What is the difference between = and ==?

    = stores a value in a variable, == compares two values and gives True or False.

2

Computing with angles: the math module

20 min
You will learn

the operators, the math module, radians and degrees, and how to compute the end of a robot link with cos and sin, and an angle with atan2.

In one sentence

The functions of math work in radians: convert with math.radians before cos and sin, and back with math.degrees.

2.1 Operators

OperatorMeaningExample
+ - * /the four operations7 / 2 → 3.5
//whole division7 // 2 → 3
%remainder370 % 360 → 10
**power3 ** 2 → 9

The remainder % is very useful for angles: a % 360 brings any angle back between 0 and 360°.

2.2 The end of a link

A link of length L turned by an angle θ ends at x = L cos θ, y = L sin θ (the maths course, lesson 1). In Python:

# where is the end of a link? the math module works in radians
import math

L = 0.5                        # link length (m)
theta_deg = 30                 # joint angle in degrees
theta = math.radians(theta_deg)

x = L * math.cos(theta)
y = L * math.sin(theta)
print(f"x = {x:.3f} m, y = {y:.3f} m")

# and back: the angle of a point with atan2 (right in every quadrant)
angle = math.degrees(math.atan2(y, x))
print(f"angle = {angle:.1f} deg")
x = 0.433 m, y = 0.250 m
angle = 30.0 deg
  • import math loads the module once, at the top of the file.
  • f"x = {x:.3f}" is an f-string: the value of x is written with 3 decimals.
  • math.atan2(y, x) gives the angle of a point in every quadrant; math.atan(y / x) gets it wrong when x is negative.
The most common bug in robot code

Passing degrees to math.cos: math.cos(90) is −0.448, not 0, because 90 is read as 90 radians. Always convert: math.cos(math.radians(90)) ≈ 0.

Key terms

  • operator
  • module, import
  • radian
  • f-string
  • atan2

Exercises

Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.

Level 1 · Beginner1

A link of length L = 0.8 m is turned by 60°. What does 0.8 * math.cos(math.radians(60)) give (in m)?

Solution

Rule used end of a link: x = L cos θ, with θ in radians for math.cos lesson 2 — 2.2 The end of a link

StepValue
math.radians(60)1.047
math.cos(1.047)0.5
0.8 * 0.50.4

Answer x = 0.4 m

Level 1 · Beginner2

What does math.degrees(math.atan2(1, -1)) give (in degrees)?

Solution

Rule used atan2(y, x) gives the angle of the point (x, y) in every quadrant; note the order: y first lesson 2 — 2.2, list under the program

  1. y = 1 and x = −1: the point is up and to the left, between 90° and 180°.
  2. |y| = |x|, so it is at 45° from the negative x axis: 180° − 45° = 135°.
  3. atan2 gives 2.356 rad; math.degrees turns it into 135.

Answer 135°

Level 2 · Intermediate3

What does -30 % 360 give?

Hint

In Python the remainder % has the sign of the divisor (here 360, positive).

Solution

Rule used a % 360 brings any angle back between 0 and 360° lesson 2 — 2.1 Operators (table and the line below)

  1. Find the whole number of turns below −30: −30 // 360 = −1.
  2. Remainder = −30 − (−1 × 360) = −30 + 360 = 330.
  3. Check: −30° and 330° are the same direction.

Answer 330

Check yourself
  1. What does 370 % 360 give?

    10: the remainder of the division, useful to bring an angle back between 0 and 360°.

  2. Why does math.cos(90) not give 0?

    Because math works in radians: 90 is read as 90 rad. Use math.cos(math.radians(90)).

  3. Which function gives the angle of the point (−1, 1) correctly?

    math.atan2(1, −1) → 135°.

3

Deciding and repeating: conditions and loops

25 min
You will learn

if, elif and else to take a decision (a joint at its limit), for and while to repeat (a list of points, a control loop), and why indentation matters.

In one sentence

if chooses which lines run; for repeats over a list; while repeats as long as a condition is true — and the indented lines are the ones inside.

3.1 A joint and its limits

# check a joint against its limits, then move it step by step
LOW, HIGH = -90, 90            # joint limits in degrees

def check(angle):
    if angle < LOW:
        return "too low"
    elif angle > HIGH:
        return "too high"
    else:
        return "ok"

for a in [-120, 0, 45, 100]:
    print(a, check(a))

# a simple loop: move from 0 to 60 degrees in steps of 15
angle = 0
while angle < 60:
    angle += 15
    print("joint at", angle)
-120 too low
0 ok
45 ok
100 too high
joint at 15
joint at 30
joint at 45
joint at 60
KeywordWhat it doesIn a robot
if / elif / elseruns the first block whose condition is truerefuse an angle outside the limits, react to a sensor
for x in …repeats once for each elementvisit every waypoint, every joint
while condition:repeats as long as the condition is truethe control loop: read, compute, command
breakleaves the loop at oncestop when the emergency button is pressed

3.2 The loop of every robot

Every robot runs the same loop, many times per second: read the sensors, compute what to do, command the motors, wait for the next period. In Python it is a while loop; on a microcontroller it is the loop() function of the electronics course.

Indentation

Use 4 spaces for each level. A line that is not indented any more is after the block, not inside it. A missing or extra space gives an IndentationError or, worse, a program that does something else.

Key terms

  • condition
  • if / elif / else
  • for, while
  • indentation
  • control loop

Exercises

Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.

Level 1 · Beginner1

How many lines does for k in range(5): print(k) print?

Solution

Rule used for repeats once for each element; range(5) gives 0, 1, 2, 3, 4 lesson 3 — 3.1 (table of keywords)

  1. range(5) starts at 0 and stops before 5.
  2. That is 5 values, so 5 lines: 0 1 2 3 4.

Answer 5 lines

Level 2 · Intermediate2

angle = 0, then while angle < 60: angle = angle + 25. What is angle after the loop?

Hint

Write the value of angle and the test at each turn.

Solution

Rule used while tests the condition before each turn and stops as soon as it is false lesson 3 — 3.1 (table of keywords)

Turnangle beforeangle < 60?angle after
10yes25
225yes50
350yes75
—75no: stop75

Answer 75 — the loop goes past 60 because it adds 25 before testing again

Check yourself
  1. How many times does “for a in [-120, 0, 45, 100]” run?

    4 times, once for each element of the list.

  2. In the program, why does the while loop stop at 60?

    Because the condition angle < 60 becomes false once angle reaches 60.

  3. What are the three steps of the loop of every robot?

    Read the sensors, compute, command the motors (then wait for the next period).

4

Functions: the forward kinematics of an arm

25 min
You will learn

how to write a function with def, give it parameters and default values, return several results, and turn the forward kinematics of a 2-link arm into one reusable line.

In one sentence

A function packs a calculation under a name: you write it once, test it once, and call it everywhere.

4.1 The forward kinematics as a function

x = L1 cos θ1 + L2 cos(θ1 + θ2)   y = L1 sin θ1 + L2 sin(θ1 + θ2)

# a function for the forward kinematics of a 2-link arm
import math

def fk(theta1, theta2, L1=0.5, L2=0.4):
    """Angles in degrees -> position (x, y) of the tool in metres."""
    t1 = math.radians(theta1)
    t12 = math.radians(theta1 + theta2)
    x = L1 * math.cos(t1) + L2 * math.cos(t12)
    y = L1 * math.sin(t1) + L2 * math.sin(t12)
    return x, y

x, y = fk(30, 45)
print(f"tool at ({x:.3f}, {y:.3f}) m")
print(fk(0, 0))            # arm stretched along x: (0.9, 0.0)
tool at (0.537, 0.636) m
(0.9, 0.0)
  • def fk(theta1, theta2, L1=0.5, L2=0.4): — two required parameters and two with a default value.
  • The text between triple quotes is the docstring: it says what goes in and what comes out, with the units.
  • return x, y returns two values; x, y = fk(30, 45) takes them apart.
Always test a function with a pose you know

With all the angles at 0 the arm is stretched along x: fk(0, 0) must give (0.9, 0). With θ₁ = 90°, θ₂ = 0 it points up: (0, 0.9). Two lines of test catch most mistakes (degrees forgotten, sin and cos swapped).

Key terms

  • function, def
  • parameter, default value
  • return
  • docstring
  • forward kinematics

Exercises

Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.

Level 1 · Beginner1

With the function fk of the lesson (L1 = 0.5, L2 = 0.4), what is y for fk(90, 0) (in m)?

Solution

Rule used forward kinematics: y = L1 sin θ1 + L2 sin(θ1 + θ2) lesson 4 — 4.1 The forward kinematics as a function

  1. θ1 = 90°, θ1 + θ2 = 90°: both links point up.
  2. y = 0.5 × sin 90° + 0.4 × sin 90° = 0.5 + 0.4.

Answer y = 0.9 m (and x = 0)

Level 2 · Intermediate2

What is x for fk(90, -90) (in m)?

Hint

θ1 + θ2 = 0: the second link is horizontal.

Solution

Rule used forward kinematics: x = L1 cos θ1 + L2 cos(θ1 + θ2) lesson 4 — 4.1 The forward kinematics as a function

TermAnglecosValue (m)
L1 cos θ190°00
L2 cos(θ1 + θ2)0°10.4
sum x0.4

Answer x = 0.4 m (and y = 0.5 m): the arm makes an L

Check yourself
  1. What does fk(0, 0) return with L1 = 0.5 and L2 = 0.4?

    (0.9, 0.0): the arm is stretched along x.

  2. How do you call fk with an arm of L1 = 1 and L2 = 1?

    fk(30, 45, L1=1, L2=1) — the default values are replaced.

  3. Why write a docstring?

    To say what goes in and what comes out, with the units (degrees, metres): the reader and you in six months need it.

5

Lists and dictionaries: waypoints and parameters

25 min
You will learn

how to keep many values together: a list for an ordered path of waypoints, a tuple for a fixed pair, a dictionary for the named parameters of a robot.

In one sentence

A list is numbered from 0 and keeps the order; a dictionary finds a value by its name.

5.1 Three containers

ContainerWrittenRead one valueIn a robot
list[0, 30, 60]pts[0], pts[-1]a path, the samples of a sensor
tuple(30, 45)p[1]one pose (θ₁, θ₂), a point (x, y)
dictionary{"L1": 0.5}robot["L1"]the parameters of a robot, a configuration file
# a list of waypoints and a dictionary of robot parameters
robot = {"name": "arm2", "L1": 0.5, "L2": 0.4, "max_speed": 90}   # dict: key -> value
waypoints = [(0, 0), (30, 45), (60, -30), (90, 0)]               # list of tuples (theta1, theta2)

print("robot", robot["name"], "with", len(waypoints), "waypoints")
for i, (t1, t2) in enumerate(waypoints):
    print(f"point {i}: theta1 = {t1}, theta2 = {t2}")

waypoints.append((0, 0))                 # go back home at the end
print("last point:", waypoints[-1], "- total:", len(waypoints))
robot arm2 with 4 waypoints
point 0: theta1 = 0, theta2 = 0
point 1: theta1 = 30, theta2 = 45
point 2: theta1 = 60, theta2 = -30
point 3: theta1 = 90, theta2 = 0
last point: (0, 0) - total: 5
  • The first element is number 0; [-1] is the last one.
  • len(pts) gives the number of elements; pts.append(p) adds one at the end.
  • for i, (t1, t2) in enumerate(pts) gives at the same time the number and the two angles of each point.
Why a dictionary for the parameters?

robot["L1"] says what it is; robot[1] does not. The configuration files of ROS 2 (YAML) and of most robots are read in Python as dictionaries.

Key terms

  • list, index
  • tuple
  • dictionary, key
  • len, append
  • enumerate

Exercises

Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.

Level 1 · Beginner1

The list pts has 4 points. After pts.append((0, 0)) twice, what is len(pts)?

Solution

Rule used append adds one element at the end; len counts the elements lesson 5 — 5.1, list under the program

  1. Start: 4 elements.
  2. Each append adds 1: 4 + 1 + 1 = 6.

Answer 6

Level 1 · Beginner2

With pts = [(0, 0), (30, 45), (60, -30)], what is pts[-1]?

  1. (0, 0)
  2. (60, -30)
  3. (30, 45)
  4. an error

Solution

Rule used index −1 is the last element of a list lesson 5 — 5.1, list under the program

Index012
from the end−3−2−1
element(0, 0)(30, 45)(60, -30)

Answer (60, -30) (B)

Level 2 · Intermediate3

With robot = {"L1": 0.5, "L2": 0.4}, what does robot["L1"] + robot["L2"] give? (It is the reach of the arm, in m.)

Solution

Rule used a dictionary gives the value stored under a key: robot["L1"] lesson 5 — 5.1 Three containers (table)

  1. robot["L1"] → 0.5 and robot["L2"] → 0.4.
  2. 0.5 + 0.4 = 0.9: the arm stretched reaches 0.9 m.

Answer 0.9 m

Check yourself
  1. What is waypoints[0] in the program?

    (0, 0): the first point, number 0.

  2. How do you read the length L2 of the robot?

    robot["L2"] → 0.4.

  3. When is a tuple better than a list?

    For a small fixed group of values that belong together, such as one pose (θ₁, θ₂): it cannot be changed by mistake.

6

NumPy: vectors, matrices, whole trajectories

30 min
You will learn

how NumPy stores vectors and matrices, the matrix product @, a rotation matrix as a function, and how to compute a whole trajectory in one line instead of a loop.

In one sentence

NumPy turns the maths of the course into code almost word for word: a vector is np.array, a product of matrices is @.

6.1 A rotation in code

R(θ) = [[cos θ, −sin θ], [sin θ, cos θ]]   a′ = R(θ) a

# NumPy: vectors, matrices and a whole trajectory at once
import numpy as np

a = np.array([0.3, 0.4])
print("length of a:", np.linalg.norm(a))          # 0.5

def rot(deg):
    t = np.radians(deg)
    return np.array([[np.cos(t), -np.sin(t)],
                     [np.sin(t),  np.cos(t)]])

print("a turned by 90 deg:", rot(90) @ a)          # @ = matrix product

t = np.linspace(0, 2, 5)                           # 5 instants from 0 to 2 s
theta = 90 * t / 2                                 # a joint going from 0 to 90 deg
print("t     =", t)
print("theta =", theta)
length of a: 0.5
a turned by 90 deg: [-0.4  0.3]
t     = [0.  0.5 1.  1.5 2. ]
theta = [ 0.  22.5 45.  67.5 90. ]
MathsNumPy
vector anp.array([0.3, 0.4])
length ‖a‖np.linalg.norm(a)
product of matrices R aR @ a
transpose Rᵀ, inverse R⁻¹R.T, np.linalg.inv(R)
n instants from 0 to Tnp.linspace(0, T, n)

6.2 No loop needed

theta = 90 * t / 2 computes the 5 angles at once, because t is an array: every operation is done on every element. This is shorter and about 100 times faster than a for loop on long trajectories.

* is not @

A * B multiplies element by element; the matrix product of the maths course is A @ B. Mixing them up gives a result of the right size but wrong values.

Key terms

  • NumPy, array
  • matrix product @
  • norm
  • linspace
  • vectorised computation

Exercises

Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.

Level 1 · Beginner1

What does np.linalg.norm(np.array([3, 4])) give?

Solution

Rule used the norm is the length of the vector: √(x² + y²) lesson 6 — 6.1 (table maths → NumPy)

  1. 3² + 4² = 9 + 16 = 25.
  2. √25 = 5.

Answer 5.0

Level 1 · Beginner2

What is the step between two values of np.linspace(0, 1, 5)?

Solution

Rule used linspace(a, b, n) gives n values, ends included, so n − 1 intervals: step = (b − a) / (n − 1) lesson 6 — 6.1 (program and table)

  1. 5 values make 4 intervals.
  2. step = (1 − 0) / 4 = 0.25: [0, 0.25, 0.5, 0.75, 1].

Answer 0.25

Level 2 · Intermediate3

With the function rot of the lesson, what is rot(90) @ np.array([1, 0])?

  1. [0, 1]
  2. [1, 0]
  3. [0, −1]
  4. [−1, 0]

Solution

Rule used R(θ) a turns a by θ counter-clockwise; R(90°) = [[0, −1], [1, 0]] lesson 6 — 6.1 A rotation in code (and the figure)

Row of R× (1, 0)Result
[0, −1]0 × 1 + (−1) × 00
[1, 0]1 × 1 + 0 × 01

Answer [0, 1] (A): the x axis turned by 90° becomes the y axis (NumPy prints [6.1e-17, 1.] because of rounding)

Check yourself
  1. What does np.linalg.norm(np.array([3, 4])) give?

    5.0 = √(3² + 4²).

  2. What is the difference between R * a and R @ a?

    R * a multiplies element by element; R @ a is the matrix product (the rotation).

  3. How many values does np.linspace(0, 2, 5) give, and what is the step?

    5 values, step 0.5: [0, 0.5, 1, 1.5, 2].

7

Plots and data files: seeing what the robot does

25 min
You will learn

how to draw a curve with Matplotlib (axes, labels, legend, grid), how to save it, and how to read a file of measurements and compute its mean and standard deviation.

In one sentence

Never trust a trajectory or a sensor you have not plotted.

7.1 Plot a joint trajectory

The program draws the smooth law of degree 5 of the maths course (lesson 7): the joint goes from 0 to 90° in 2 s, starting and stopping with zero speed and acceleration.

# plot a joint trajectory and read sensor data from a file
import numpy as np
import matplotlib.pyplot as plt

t = np.linspace(0, 2, 200)
s = 10 * (t / 2)**3 - 15 * (t / 2)**4 + 6 * (t / 2)**5     # smooth law from 0 to 1
theta = 90 * s                                            # degrees

plt.plot(t, theta, label="theta (deg)")
plt.xlabel("time (s)"); plt.ylabel("angle (deg)"); plt.legend(); plt.grid()
plt.savefig("trajectory.png")                              # or plt.show()

data = np.loadtxt("distance.csv", delimiter=",")           # one column of measurements (m)
print(f"mean = {data.mean():.3f} m, std = {data.std():.3f} m, n = {data.size}")

The picture saved in trajectory.png looks like the figure above. Then the program reads 10 measurements of a distance sensor pointed at a wall 1 m away:

mean = 1.000 m, std = 0.019 m, n = 10
LineWhat the line does
plt.plot(t, theta, label=…)draws theta against t and names the curve
plt.xlabel / ylabel / legend / gridthe names of the axes with units, the legend, the grid
plt.savefig("….png")saves the picture (plt.show() opens a window)
np.loadtxt("….csv", delimiter=",")reads a text file of numbers into an array
data.mean(), data.std()the mean and the standard deviation (the noise of the sensor)
A good plot in four checks
  1. each axis has a name and a unit;
  2. each curve has a label and the legend does not hide it;
  3. the start and end values are the expected ones (0 and 90° here);
  4. there is no jump: a jump in a position means an infinite speed.

Key terms

  • Matplotlib
  • label, legend
  • CSV file
  • mean
  • standard deviation

Exercises

Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.

Level 1 · Beginner1

On the curve of the lesson (0 to 90° in 2 s), what is the angle at t = 1 s (in degrees)?

Solution

Rule used smooth law of degree 5: s(u) = 10u³ − 15u⁴ + 6u⁵ with u = t / T, then θ = 90 s lesson 7 — 7.1 Plot a joint trajectory

Termu = 0.5
10u³1.25
−15u⁴−0.9375
6u⁵0.1875
s = sum0.5

Answer θ = 90 × 0.5 = 45°

Level 2 · Intermediate2

A sensor gives 0.98, 1.00 and 1.02 m. What does data.mean() give (in m)?

Solution

Rule used mean = sum of the values / number of values lesson 7 — 7.1 (table, last line)

  1. Sum: 0.98 + 1.00 + 1.02 = 3.00.
  2. Divide by 3: 3.00 / 3 = 1.00.

Answer 1.00 m

Check yourself
  1. What is the angle at t = 1 s on the curve?

    45°: the smooth law is symmetric, half the motion is done at half the time.

  2. What does the standard deviation of the 10 measurements tell you?

    The size of the sensor noise: about 0.019 m = 1.9 cm here.

  3. What is the difference between plt.savefig and plt.show?

    savefig writes the picture into a file; show opens it in a window.

8

Classes and a first controller

30 min
You will learn

how a class groups the data of a robot and its functions, what self and __init__ are, and how to write the loop of a proportional controller that brings a joint to a target.

In one sentence

A class is a mould for objects: Arm2() makes a robot that keeps its own lengths and angles and knows how to compute its tool.

8.1 The class Arm2

  • __init__ runs when the object is made: it stores L1, L2 and the angles q in self.
  • self is “this robot”: two objects Arm2() have their own angles.
  • tool() is a method: a function that uses the data of the object (the forward kinematics of lesson 4).

8.2 A proportional controller

e = qtarget − q   ω = Kp e   q ← q + ω Δt

# a small robot class and a proportional controller on one joint
import math

class Arm2:
    def __init__(self, L1=0.5, L2=0.4):
        self.L1, self.L2 = L1, L2
        self.q = [0.0, 0.0]                      # joint angles in degrees

    def tool(self):
        t1, t12 = math.radians(self.q[0]), math.radians(self.q[0] + self.q[1])
        return (self.L1 * math.cos(t1) + self.L2 * math.cos(t12),
                self.L1 * math.sin(t1) + self.L2 * math.sin(t12))

arm = Arm2()
target, Kp, dt = 60.0, 4.0, 0.05                 # P controller on joint 1
for k in range(6):
    error = target - arm.q[0]
    speed = Kp * error                           # deg/s
    arm.q[0] += speed * dt
    print(f"step {k}: q1 = {arm.q[0]:5.1f} deg, error = {error:5.1f}")
print("tool at (%.2f, %.2f) m" % arm.tool())
step 0: q1 =  12.0 deg, error =  60.0
step 1: q1 =  21.6 deg, error =  48.0
step 2: q1 =  29.3 deg, error =  38.4
step 3: q1 =  35.4 deg, error =  30.7
step 4: q1 =  40.3 deg, error =  24.6
step 5: q1 =  44.3 deg, error =  19.7
tool at (0.64, 0.63) m

At each step the error is multiplied by 1 − KpΔt = 1 − 4 × 0.05 = 0.8: 60 → 48 → 38.4 → … The joint gets closer and closer without overshoot. A larger Kp is faster, but if KpΔt > 2 the error changes sign and grows at every step: the loop is unstable.

Where to go next

The PID of the control course adds an integral term (no error left at the end) and a derivative term (less overshoot). In ROS 2 the same class becomes a node (ROS 2 course, lesson 3), and on a microcontroller the same loop becomes loop() (electronics course).

Key terms

  • class, object
  • __init__, self
  • method
  • proportional controller
  • gain Kp, period Δt

Exercises

Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.

Level 1 · Beginner1

In the controller of the lesson, take Kp = 2 instead of 4 (Δt = 0.05, target 60°, start 0°). What is q1 after the first step (in degrees)?

Solution

Rule used P controller: e = target − q, ω = Kp e, q ← q + ω Δt lesson 8 — 8.2 A proportional controller

QuantityValue
e = 60 − 060°
ω = 2 × 60120 °/s
q = 0 + 120 × 0.056°

Answer 6° — half of the 12° of the lesson: half the gain, half the step

Level 2 · Intermediate2

Still with Kp = 2, what is the error after 2 steps (in degrees)?

Hint

At each step the error is multiplied by 1 − Kp Δt.

Solution

Rule used at each step the error is multiplied by 1 − Kp Δt lesson 8 — 8.2, paragraph under the figure

  1. 1 − Kp Δt = 1 − 2 × 0.05 = 0.9.
Step kError (°)q1 (°)
0600
160 × 0.9 = 546
254 × 0.9 = 48.611.4

Answer 48.6°

Level 3 · Professional3

Which gain makes the loop unstable with Δt = 0.05 s?

  1. Kp = 4 /s
  2. Kp = 20 /s
  3. Kp = 35 /s
  4. Kp = 50 /s

Solution

Rule used the loop is stable if |1 − Kp Δt| < 1, that is 0 < Kp Δt < 2 lesson 8 — 8.2, paragraph under the figure

KpKp Δt1 − Kp ΔtBehaviour
40.20.8smooth
2010reaches the target in 1 step
351.75−0.75oscillates but converges
502.5−1.5oscillates and grows: unstable

Answer Kp = 50 /s (D)

Check yourself
  1. What is the error after the first step of the program?

    48: q1 went from 0 to 12 and the target is 60.

  2. Why does q1 never quite reach 60 in 6 steps?

    Because each step only removes 20 % of the remaining error; it gets closer and closer (exponentially).

  3. What happens with Kp = 50 and Δt = 0.05?

    Kp Δt = 2.5 > 2: the error is multiplied by −1.5 at each step, the joint oscillates more and more — unstable.

Glossary

All the words of the course in one place.

TermMeaning
VariableA name that holds a value: L1 = 0.5.
TypeThe kind of a value: int, float, str, bool, list, dict…
Module, importA file of ready-made functions loaded with import (math, numpy).
RadianThe unit of angles used by math.cos and np.cos: 180° = π rad.
IndentationThe spaces at the start of a line that say which block it belongs to.
Loop (for, while)Lines repeated for each element, or as long as a condition is true.
Function, returnA named calculation: def fk(…): … return x, y.
List, indexAn ordered sequence numbered from 0; [-1] is the last element.
DictionaryValues found by a name (a key): robot["L1"].
NumPy arrayA vector or matrix; operations apply to every element at once.
Matrix product @The product of the maths course (R @ a); * is element by element.
Class, object, methodA mould (class) that makes objects holding their data and their functions (methods).
Proportional controllerA command proportional to the error: ω = Kp (target − q).

Sources and references

This course was written from these books, papers, standards and documentation. They are also the best way to go further.

  1. The Python Tutorial, docs.python.org/3/tutorial (Python Software Foundation). used for: the language: types, loops, functions, lists, dictionaries, classes
  2. NumPy documentation, numpy.org/doc. used for: vectors, matrices, linspace
  3. C. R. Harris et al., “Array programming with NumPy”, Nature, 585, 2020. used for: why array computing is fast
  4. J. D. Hunter, “Matplotlib: a 2D graphics environment”, Computing in Science & Engineering, 9(3), 2007; matplotlib.org. used for: plots
  5. J. J. Craig, Introduction to Robotics: Mechanics and Control, 4th ed., Pearson, 2017. used for: forward kinematics of the 2-link arm
  6. K. J. Åström, R. M. Murray, Feedback Systems: An Introduction for Scientists and Engineers, 2nd ed., Princeton University Press, 2021 (free online). used for: the proportional controller and its stability

You can now program a robot in Python!

Next: the electronics and Arduino course to make a real motor turn, “Code a robot arm in Python” for a full DH engine and inverse kinematics, and ROS 2 from zero to run your code on a real robot.

Back to the roadmap → Home page