# Robotics Foundations

*Tactiverge Academy course pack · version 1.0.0*

What robots are, how they are put together, how they sense and move, and the mathematics and feedback ideas that let them act on purpose in a changing world.

**Audience:** Curious students aged 13 and over. Comfortable with basic algebra; no hardware, lab or prior robotics experience needed.

> This work is licensed under the Creative Commons Attribution 4.0 International licence (CC BY 4.0): https://creativecommons.org/licenses/by/4.0/. Attribute as: Tactiverge Academy, https://tactiverge.win.



---

# Module 1: Introduction to robotics

What separates a robot from an ordinary machine, and the basic vocabulary engineers use to describe how a robot can move.

**Objectives**

- Describe a robot in terms of the sense–think–act loop and apply it to real machines.
- Distinguish automation, teleoperation and autonomy, and explain why most robots sit somewhere between them.
- Count the degrees of freedom of simple mechanisms, including your own arm.
- Explain the difference between revolute and prismatic joints and what a workspace is.


## 1.1 What makes a machine a robot?

*The sense–think–act loop, the spectrum from remote control to autonomy, and why the physical world makes robotics hard.* (about 25 min)

### A question with a fuzzy answer

Ask ten engineers to define "robot" and you will get ten slightly different answers. A washing machine follows a programme and moves water and clothes around — is it a robot? A drone that a person flies with a controller — is that one? A self-driving delivery vehicle almost certainly counts. Somewhere between these examples a line gets crossed, and it is worth understanding where.

The most useful working definition is not about what a robot looks like. Robots do not need arms, faces or legs. Instead, the definition is about what a robot **does**:

> A robot is a machine that senses its environment, decides what to do based on what it senses, and acts physically on the world.

This is often shortened to **sense, think, act**. All three parts matter, and the interesting engineering happens in the connections between them.

### Sense, think, act

**Sense.** A robot needs some way of measuring the world and itself. Sensors convert a physical quantity — light, distance, force, rotation, temperature — into a signal a computer can read. A robot vacuum might use bump switches, wheel encoders that count how far each wheel has turned, and a distance sensor that notices a staircase edge.

**Think.** Some computation turns sensor readings into decisions. This can be as simple as "if the bump switch is pressed, reverse and turn" or as complicated as building a map of a whole house. Engineers often call this part *control* or *planning*. It usually runs on a small computer or a microcontroller inside the robot.

**Act.** Actuators turn decisions back into physical effects. Electric motors spin wheels or rotate joints; other actuators include pumps, pneumatic cylinders and even speakers or lights. Acting changes the world — and changes what the sensors will measure next.

That last point is the key idea. Sense, think and act are not a straight line; they form a **loop**. The robot acts, the world responds, the robot senses the new situation, and the cycle repeats, often hundreds or thousands of times per second.

### Testing the definition

Let us apply the loop to the examples above.

- **A basic washing machine** follows a fixed timed programme. Many modern ones do sense things (water level, drum imbalance) and adjust. It sits near the boundary: it senses a little and acts, but its decisions are narrow.
- **A remote-controlled drone** senses a lot (it keeps itself level using motion sensors) but a human makes the high-level decisions. It is partly a robot.
- **A robot vacuum** senses obstacles, decides where to go next and drives itself. It clearly completes the loop.

The point of this exercise is not to win an argument about labels. It is to notice that robots exist on a spectrum, and that the questions "what does it sense?", "who or what decides?" and "how does it act?" tell you a great deal about any machine.

### The autonomy spectrum

Engineers usually describe three broad ways a robot can be controlled:

1. **Teleoperation.** A person makes the decisions in real time, and the robot carries them out. Bomb-disposal robots and surgical robots commonly work this way: the precision and reach are the machine's, the judgment is the human's.
2. **Automation.** The robot repeats a pre-planned sequence with little or no sensing. A factory arm that welds the same point on every car body is a classic example. It works brilliantly when the world is arranged exactly as expected, and poorly when it is not.
3. **Autonomy.** The robot senses its situation and chooses its own actions to reach a goal, adapting when things change.

Most real systems mix these. A Mars rover, for example, receives goals from people on Earth but must handle the details of driving itself, because radio signals take minutes to travel between the planets — far too long for a human to steer around a rock in real time.

### Why robotics is hard

Programming a computer to sort a list is a solved problem: the list does not fight back. Robots work in the physical world, and the physical world is messy in at least three ways.

- **Sensors are imperfect.** Every measurement has noise (small random errors), and some sensors drift or fail in particular conditions. A camera struggles in glare; a distance sensor may be confused by glass.
- **Actuators are imperfect.** Commanding a motor to turn exactly 90° rarely produces exactly 90°. Gears have slack, wheels slip, and loads vary.
- **The world changes.** People walk by, objects move, surfaces differ. A plan that was correct a second ago may be wrong now.

This is why the sense–think–act loop matters so much. A robot that only follows a plan cannot correct its mistakes. A robot that keeps sensing can notice that it has drifted off course and fix it. You will study this idea in detail in the module on feedback control.

### Robotics is a team sport

Building even a simple robot draws on several fields at once: mechanical engineering (structure, joints, gears), electrical engineering (power, motors, sensors), computer science (software, algorithms) and mathematics (geometry, rates of change, probability). The other pathways in this academy — embedded systems, computational engineering and mechanical design — each cover one of these pieces in depth. Robotics is where they meet.

> **Try this without any equipment.** Pick a machine you use every day — a lift, an automatic door, a phone, a microwave. Write down what it senses, who or what decides, and how it acts. Is the loop closed, or does it just follow a timer? There is no single right answer; the reasoning is the point.

#### Check your understanding

1. Which description best matches the working definition of a robot used in this lesson?
   A) A machine that senses, decides and acts physically on the world
   B) Any machine with a humanoid shape
   C) Any device controlled by a computer program
   D) A machine that moves without electricity

2. A factory arm welds the same spot on every car body, with almost no sensing. This is best described as:
   A) Teleoperation
   B) Autonomy
   C) Not a machine at all
   D) Automation

3. Why do Mars rovers need to handle some driving decisions by themselves?
   A) Mars has no gravity
   B) Humans are not allowed to control space robots
   C) Radio signals take minutes to travel between Earth and Mars, too long for real-time steering
   D) Their cameras cannot send images to Earth

4. Why is it important that sense, think and act form a loop rather than a one-way sequence?
   A) Loops use less electricity
   B) Continued sensing lets the robot notice and correct errors caused by imperfect actuators and a changing world
   C) It makes the robot look more intelligent
   D) It means the robot never needs a computer


## 1.2 Joints, degrees of freedom and workspace

*How engineers describe the ways a robot can move: joint types, counting degrees of freedom, and the region a robot can reach.* (about 30 min)

### Describing motion precisely

When engineers design or compare robots, they need precise words for how a robot can move. Saying "it has an arm that bends a lot" is not useful. Saying "it is a six-degree-of-freedom arm with revolute joints and a reach of 80 cm" tells another engineer almost everything they need to know about its basic capabilities. This lesson introduces that vocabulary.

### Links and joints

Most robots that move parts of themselves are built from **links** (the rigid pieces) and **joints** (the connections between them that allow motion). Your own arm is a good model: your upper arm and forearm are links; your shoulder, elbow and wrist are joints.

There are two joint types you will meet constantly:

- **Revolute joints** rotate around an axis, like a door hinge or your elbow. Their position is described by an angle.
- **Prismatic joints** slide along a straight line, like a drawer or a telescope tube. Their position is described by a distance.

Many other joints exist — ball joints, screw joints, and so on — but they can usually be thought of as combinations of these two simple types.

### What is a degree of freedom?

A **degree of freedom** (often abbreviated **DOF**) is one independent way something can move. "Independent" means you can change it without having to change any of the others.

Start with a free object. A bead on a straight wire can only slide along the wire: one degree of freedom. A hockey puck on ice can slide left–right, slide forward–back and spin: three degrees of freedom. A completely free object floating in space — a satellite, say — has **six**:

1. Move along x (forward–back)
2. Move along y (left–right)
3. Move along z (up–down)
4. Rotate about x (often called roll)
5. Rotate about y (pitch)
6. Rotate about z (yaw)

Three of these are **translations** (moving the object's position) and three are **rotations** (changing which way it faces). Together, position and orientation are called the object's **pose**.

### Counting degrees of freedom in a robot arm

For a simple robot arm made as a chain of links — one after another, like a finger — the rule is pleasantly simple: each single-axis joint (revolute or prismatic) adds one degree of freedom. A chain with three revolute joints has three degrees of freedom.

This leads to an important fact. To place a tool anywhere in 3D space **and** point it in any direction, a robot needs at least six degrees of freedom, because a free object has six. That is why so many industrial arms have six joints. A robot with fewer joints can still be extremely useful — it just cannot reach every pose. For example, a robot that only needs to pick objects off a flat table and drop them elsewhere might manage with four.

Robots with *more* degrees of freedom than a task strictly needs are called **redundant**. Your arm is one: with your hand flat on a table, you can still move your elbow around. Redundancy gives flexibility, such as reaching around an obstacle, at the cost of more complex control.

### Worked example: your own arm

Let us count roughly, using the same rule.

- **Shoulder:** you can raise your arm forward, raise it out to the side, and twist it. That is about 3 rotations.
- **Elbow:** it bends and straightens: 1.
- **Forearm:** you can rotate your palm up and down while keeping your elbow still: 1.
- **Wrist:** it bends up–down and side to side: 2.

Total: about **7 degrees of freedom** from shoulder to wrist, not counting fingers. Biologists and roboticists model the human arm in slightly different ways, so you may see small differences in other sources, but seven is the common figure. Because seven is more than six, your arm is redundant — which matches the elbow experiment above.

### Workspace

The **workspace** of a robot is the set of all points its tool (often called the *end effector*) can reach. It depends on link lengths and on joint limits — the angles or distances each joint can physically achieve.

Picture a flat arm with two revolute joints and links of 10 cm and 8 cm, where the joints can rotate freely. Fully stretched out, it reaches 18 cm from its base. Folded back on itself, its tip sits 2 cm from the base. Every distance in between is reachable, so the workspace is a ring (an annulus) with inner radius 2 cm and outer radius 18 cm. The middle 2 cm circle is unreachable. In the module on the mathematics of movement you will see exactly why, using a little trigonometry.

Real joints have limits, cables that cannot twist forever, and parts that bump into each other, so real workspaces are usually smaller and more oddly shaped than these ideal ones.

### Mobile robots are different

A wheeled robot driving on a floor has a pose with three numbers: its x position, its y position and its heading angle. But a car-like robot cannot slide sideways; it must drive forward or backward while turning. It can still *reach* any pose on the floor (think of parallel parking), but it cannot move in any direction *instantly*. Engineers describe this by saying it has fewer controllable directions of motion at any moment than it has pose variables. You do not need the formal theory yet — just notice that "how many numbers describe where it is" and "which directions it can move right now" are two different questions.

#### Project: Paper project: a degrees-of-freedom survey

Choose **three** mechanisms from everyday life — for example a desk lamp with hinges, a pair of scissors, a door, a drawer, a bicycle, a folding chair or a toy crane.

For each one, sketch it on paper as links (straight lines) and joints (circles for revolute, small rectangles for prismatic). Then count its degrees of freedom and describe, in a sentence or two, what its workspace looks like.

Finally, pick one and propose a single extra joint that would make it more useful. Explain what the new degree of freedom would let it do.

**Deliverables**

- Three labelled link-and-joint sketches
- A DOF count and workspace description for each mechanism
- A short proposal for one added joint and what it would enable

#### Check your understanding

1. A drawer sliding in and out of a desk is an example of which joint type?
   A) Revolute
   B) Ball
   C) Redundant
   D) Prismatic

2. How many degrees of freedom does a completely free rigid object in 3D space have?
   A) 3
   B) 4
   C) 6
   D) 7

3. A flat two-link arm has links of 12 cm and 5 cm and joints that rotate freely. What is the outer radius of its workspace?
   A) 7 cm
   B) 12 cm
   C) 17 cm
   D) 60 cm

4. What does it mean for a robot arm to be redundant?
   A) It has more degrees of freedom than the task strictly needs
   B) It has a spare arm in case one breaks
   C) It cannot reach any point twice
   D) It has only prismatic joints

**Go further:**

- MIT OpenCourseWare — 2.12 Introduction to Robotics: https://ocw.mit.edu/courses/2-12-introduction-to-robotics-fall-2005/ — University-level course notes on robot kinematics and control. Challenging, but a good look at where these ideas lead.


## 1.3 Types of robots and where they work

*A tour of the main families of robots — manipulators, mobile, aerial, legged, soft and cooperative — and how engineers match a robot's type to the job it has to do.* (about 25 min)

### Why the shape of a robot matters

Imagine you are asked to build a robot that moves boxes. Before you choose a single motor or write a line of code, you face a bigger question: *what kind* of robot should it be? An arm bolted to the floor? A wheeled cart? A drone? Each answer leads to a completely different machine, with different strengths, weaknesses, costs and safety problems.

Engineers group robots into broad families according to how they are built and how they move. Knowing them gives you a shared vocabulary, and lets you reason about which family suits a task *before* you build the wrong thing.

### Manipulators: robots that handle things

A **manipulator** is a robot arm: usually fixed to a base, built as a chain of links and joints ending in a tool, the **end effector** — a gripper, suction cup or welding torch. Manipulators are the workhorses of factories because they repeat the same motion thousands of times a day.

Within this family, a few layouts are especially common:

- **Articulated arms** use a chain of revolute joints, usually six, rather like a human arm. They are flexible and can reach around objects, which makes them popular for welding, painting and machine loading.
- **SCARA arms** have two horizontal rotating joints plus a vertical sliding axis. They are stiff vertically and fast horizontally, which suits picking small parts and placing them on a flat surface, such as assembling electronics.
- **Cartesian (gantry) robots** move along straight x, y and z rails using prismatic joints. They are simple to control and can cover a large rectangular area. Many 3D printers and laboratory pipetting machines are built this way.
- **Parallel (delta) robots** hold a light platform with several arms working side by side. Because the heavy motors stay on the fixed frame, the moving parts are light and can move extremely fast — ideal for sorting items on a conveyor.

The trade-off running through this list is **flexibility** against **simplicity**: six revolute joints reach almost any pose but need harder mathematics; three straight rails reach only a box-shaped region but are almost trivial to control.

### Mobile robots: robots that travel

A **mobile robot** moves its whole body around an environment. Most travel on wheels, because wheels are efficient and simple on flat floors. A common design is **differential drive**: two independently driven wheels and a free-rolling caster. Driving both wheels at the same speed goes straight; driving them at different speeds turns. Robot vacuums and many warehouse robots work this way.

Mobile robots in warehouses and hospitals are sometimes split into two kinds. Older **automated guided vehicles** (AGVs) follow fixed paths marked by lines, magnetic tape or reflectors. **Autonomous mobile robots** (AMRs) build or use a map and plan their own routes, so they can drive around an unexpected obstacle instead of stopping until someone moves it.

Tracked robots trade efficiency for grip on rough ground, and underwater vessels are mobile robots too.

### Aerial robots: robots that fly

**Aerial robots**, usually called drones, come in two main types. **Multirotors** (such as quadcopters) can hover, take off vertically and hold a precise position, which makes them good for inspection and filming. Their weakness is energy: holding a body up with spinning propellers takes a lot of power, so flight times are often measured in tens of minutes. **Fixed-wing** drones fly like aeroplanes. They cover long distances efficiently but cannot hover and need space to launch and land.

Multirotors are also **unstable without control**: an onboard controller makes hundreds of small corrections per second to keep them level.

### Legged robots: robots that step

**Legged robots** — two-legged bipeds, four-legged quadrupeds, six-legged hexapods — walk rather than roll. Legs are mechanically complex and need many motors and careful balance control, so why bother? Because legs can step *over* things. Stairs, rubble, rocks and gaps that would stop a wheel are manageable for a leg that chooses where to put its foot. Quadrupeds are increasingly used for inspection in places built for people, such as industrial plants with stairs and walkways.

### Soft robots: robots that bend

Most robots are built from rigid links. **Soft robots** are made partly or wholly from flexible materials such as silicone rubber, and often move by inflating chambers with air. A soft gripper can wrap gently around a tomato or an irregular object without needing to know its exact shape, because the material itself conforms. The price is that soft bodies are harder to model and control precisely, and they usually cannot exert large forces.

### Cooperative robots: robots that work together

Some tasks are too large, too awkward or too floppy for one robot. **Cooperative robots** share a task: two arms carrying a long panel, a fleet of warehouse robots dividing up orders, or a robot and a person assembling something together. Cooperation brings new problems: the robots must agree on timing, avoid colliding, and — when they hold the same object — avoid pulling against one another. Handling floppy materials such as cloth or cable cooperatively is still an open research area.

### Matching robot type to task

Choosing a robot type is an engineering decision, and like most engineering decisions it starts with questions about the task rather than enthusiasm for a particular machine. Useful questions include:

1. **Does the robot need to go somewhere, or does the work come to it?** If parts arrive on a conveyor, a fixed manipulator is often best. If the work is spread across a building, the robot must be mobile.
2. **What is the terrain?** Smooth floors favour wheels. Stairs and rubble favour legs or tracks. Air favours drones; water favours vessels.
3. **What precision and force does the task need?** Fixed arms are stiff and precise. Soft grippers are gentle but weak.
4. **How varied are the objects and surroundings?** Repetitive tasks in a tidy space suit simple automation; varied ones need more sensing and a more flexible design.
5. **Who else is nearby?** Working alongside people changes the design — the subject of a later lesson in this module.

### Worked example

A small bakery wants help moving trays of bread rolls from an oven rack onto cooling shelves about two metres away. The trays are all the same size; the floor is flat; staff walk through the area.

- The work is spread over a short distance, but the trays always start and end in the same two places. A **single articulated arm** mounted between rack and shelves could reach both, avoiding the need to drive at all.
- If the shelves were in another room, a **mobile robot** carrying trays, perhaps with a small arm, would be needed.
- A drone is a poor choice: heavy trays cost a lot of energy, and propellers near staff are a hazard. A soft gripper is unnecessary for rigid, identical trays.

The answer came from the task, not the robot. The simplest family that meets the requirements is often right, because every extra capability adds cost and new ways to fail.

### Recap

- **Manipulators** handle objects from a fixed base; articulated, SCARA, Cartesian and delta layouts trade flexibility against simplicity and speed.
- **Mobile robots** move their whole body, usually on wheels; AMRs plan their own routes while AGVs follow fixed paths.
- **Aerial robots** reach places nothing else can but pay for it in energy; multirotors need constant control to stay up.
- **Legged robots** handle rough terrain; **soft robots** handle delicate or irregular objects; **cooperative robots** share tasks one robot cannot do alone.
- Choose a type by asking about the task first, and prefer the simplest design that does the job.

> **Families overlap.** Real robots often combine families. A **mobile manipulator** is an arm mounted on a wheeled base. A legged robot may carry an arm on its back. The families are a way of thinking, not strict boxes — when you meet a new robot, ask which family each part belongs to.

#### Project: Paper project: robot matchmaker

Write down **four** tasks from different settings — for example harvesting strawberries, inspecting a bridge, sorting parcels, cleaning a swimming pool, or helping someone fold laundry.

For each task:

1. Answer the five matching questions from this lesson in a sentence each.
2. Choose a robot family (or a combination) and sketch it roughly.
3. Name one family you rejected and explain why in a sentence.

Finally, pick the task you found hardest to match and describe what makes it difficult. No equipment is needed beyond paper and a pencil.

**Deliverables**

- Four tasks with answers to the five matching questions
- A chosen robot family and rough sketch for each
- One rejected family per task, with a reason
- A short paragraph on the hardest task

#### Check your understanding

1. Why can a parallel (delta) robot move so quickly?
   A) It uses only prismatic joints
   B) Its heavy motors stay on the fixed frame, so the moving parts are very light
   C) It has more degrees of freedom than any other arm
   D) It does not need any sensors

2. A robot must inspect equipment in a plant with stairs and narrow metal walkways. Which family is the most natural fit?
   A) A fixed articulated arm
   B) A Cartesian gantry robot
   C) A legged robot
   D) A fixed-wing drone

3. What is the main difference between an AGV and an AMR?
   A) An AMR plans its own routes using a map, while an AGV follows fixed marked paths
   B) An AGV can fly and an AMR cannot
   C) An AMR always has legs
   D) There is no difference; they are two names for the same thing

4. What is a key advantage of a soft gripper?
   A) It can exert much larger forces than a rigid gripper
   B) It is easier to model mathematically
   C) It never needs a power source
   D) It conforms to irregular or delicate objects without needing their exact shape

5. According to the lesson, what is usually the best starting point for choosing a robot type?
   A) The most advanced robot available
   B) The questions the task raises: where the work is, the terrain, precision, variety and who is nearby
   C) Whichever robot has the most degrees of freedom
   D) The cheapest motor you can find

**Go further:**

- Wikipedia — Soft robotics: https://en.wikipedia.org/wiki/Soft_robotics — An overview of soft materials, actuation methods and applications, with references to research articles.


## 1.4 The sense–think–act loop in time

*Looking closely at each stage of the robot's loop — perception, decision and action — and at the timing that decides whether the loop works at all.* (about 30 min)

### A loop that takes time

In the first lesson of this module you met the idea that a robot senses, thinks and acts in a loop. That picture is correct but incomplete, because it hides something every robot engineer worries about: **time**. Each stage takes time, the loop repeats at some rate, and the world keeps moving while the robot is busy. A robot that makes the right decision too late has made the wrong decision.

This lesson opens up each stage of the loop, then puts numbers on the timing so you can see when a loop is fast enough and when it is not.

### Sensing is really perception

A sensor produces raw data: a voltage, a count of encoder ticks, a grid of pixel brightness values. Raw data is rarely what the robot needs. A robot needs to know things like "the wall is 30 cm ahead" or "the cup is tipped over". Turning raw data into useful facts is called **perception**.

Perception has two parts worth separating:

- **Measurement**: the sensor converts a physical quantity into a number, with some noise and some delay.
- **Interpretation**: software turns those numbers into a description of the situation, often called the robot's **state estimate**. A state estimate might be as simple as one distance or as rich as a map with the robot's position on it.

Interpretation can be slow — finding an object in a camera image might take tens of milliseconds — and the result always describes the world *as it was* when the measurement was taken.

### Thinking is choosing an action

The decision stage takes the state estimate and a goal and picks what to do next. Engineers use different words for different kinds of decision:

- **Control** answers "how hard should I push right now?" — for example, how much voltage to send to a motor to hold a joint at an angle. It is usually fast, simple and repeated very often.
- **Planning** answers "what sequence of moves will get me to the goal?" — for example, a route across a room or a path for an arm around an obstacle. It is usually slower and repeated less often.

Many robots run both at once: a planner chooses where to go every second or so, and a controller steers towards the planner's current target hundreds of times per second. You will study this layering in the module on system architecture.

### Acting changes the world

Actuators carry out the decision. Like sensors, they are not instant. A motor has to accelerate its own rotor and whatever it is moving, and a command sent over a wire takes time to arrive. When the actuator moves, the world changes: the robot is in a new place, an object has shifted, a force has appeared.

### Why the loop closes through the physical world

Here is the idea that makes robotics different from pure software. There is no wire from the robot's motors back to its sensors. The only connection is the **physical world itself**. The robot pushes on the world; the world responds according to physics — mass, friction, springiness, gravity; and the sensors measure the result.

This has two consequences. First, the robot cannot simply assume its action worked. A wheel can slip; an object can be heavier than expected. The only way to know is to measure again. Second, the behaviour of the whole loop depends on the physics of whatever the robot is touching. The same controller can behave beautifully lifting a light box and badly lifting a heavy one, because the world part of the loop has changed.

### Putting numbers on timing

Two timing quantities matter most:

- **Loop period** (T): the time between one pass of the loop and the next. Its reciprocal is the **loop rate**. A loop that runs every 10 ms has a rate of 1 / 0.010 s = 100 Hz.
- **Latency** (L): the delay between something happening in the world and the robot acting on it. It includes the sensor's own delay, data transfer, perception and computing time.

While the robot waits for its next loop and for its data to arrive, it keeps moving. A useful rule of thumb is that in the worst case, the robot reacts to an event up to **T + L** seconds late. If it is moving at speed v, it travels about v · (T + L) before responding.

### Worked example

A robot drives towards a wall at 0.8 m/s. It should stop when its distance sensor reads 300 mm. Suppose its loop period is 200 ms and its readings are 80 ms old by the time they are used.

```
worst-case delay = T + L = 0.200 + 0.080 = 0.280 s
distance travelled = 0.8 m/s × 0.280 s = 0.224 m = 224 mm
```

So the robot could stop as close as 300 − 224 = 76 mm from the wall instead of 300 mm. That is a big difference for a robot trying not to scuff the paint.

The short program below simulates the same robot with different loop periods and latencies. Time is counted in whole milliseconds and distance in whole millimetres so the arithmetic is exact.

```python
# A robot drives at 0.8 m/s (0.8 mm per ms) towards a wall 1200 mm away.
# It commands "stop" as soon as a reading shows 300 mm or less.
# Whole millimetres and milliseconds keep the arithmetic exact.

def stopping_gap(loop_ms, latency_ms):
    t = 0
    while True:
        measured_at = max(t - latency_ms, 0)       # the reading is this old
        reading = 1200 - 8 * measured_at // 10      # distance it reports, mm
        if reading <= 300:
            return 1200 - 8 * t // 10               # true gap when it stops
        t += loop_ms                                # wait for the next loop

for loop_ms, latency_ms in [(10, 0), (100, 0), (100, 80), (200, 80)]:
    gap = stopping_gap(loop_ms, latency_ms)
    print(f"loop {loop_ms:3d} ms, latency {latency_ms:2d} ms: stops {gap:3d} mm from the wall")
```

Output:

```
loop  10 ms, latency  0 ms: stops 296 mm from the wall
loop 100 ms, latency  0 ms: stops 240 mm from the wall
loop 100 ms, latency 80 ms: stops 160 mm from the wall
loop 200 ms, latency 80 ms: stops  80 mm from the wall
```

The fast loop with no latency stops within 4 mm of its target. The slow loop with latency stops 220 mm late — close to the 224 mm worst case we calculated. (This model even assumes the robot stops instantly once commanded; a real robot also needs braking distance, which makes things worse.)

### How fast is fast enough?

There is no single correct loop rate. What matters is how quickly the relevant part of the world changes compared with how quickly the robot responds. A greenhouse robot checking whether soil is dry can run its loop once a minute, because soil dries slowly. A drone keeping itself level needs hundreds of corrections per second, because it starts to tip within a fraction of a second. A practical way to think about it: **the faster things change, or the faster the robot moves, the shorter T + L must be.**

When you cannot make the loop faster, you have other options: move more slowly, leave a larger safety margin, or predict where things will be by the time the action lands. All three are common engineering choices.

### Recap

- Sensing is really **perception**: measurement plus interpretation into a state estimate, which always describes the recent past.
- Thinking covers fast **control** and slower **planning**, often running together.
- The loop closes **through the physical world**, so the robot must measure to know whether its action worked, and the loop's behaviour depends on physics.
- **Loop period** and **latency** together set how late a robot can react; a moving robot travels about v · (T + L) before responding.
- Match loop timing to how fast the world changes, or compensate with lower speed, margins or prediction.

> **Interactive:** Switch on "Compare with open loop" and add a load disturbance. The open-loop command never measures, so it cannot recover; the closed loop senses the change through the world and corrects it. Then add sensor noise to see what imperfect perception does to the loop. Try it at https://tactiverge.win/academy/lab/#feedback

#### Check your understanding

1. A control loop runs every 4 ms. What is its loop rate?
   A) 4 Hz
   B) 40 Hz
   C) 250 Hz
   D) 4000 Hz

2. A robot moves at 0.5 m/s with a loop period of 100 ms and a latency of 60 ms. About how far could it travel before reacting to an event, in the worst case?
   A) 8 cm
   B) 5 cm
   C) 30 cm
   D) 0.16 cm

3. What does it mean to say the sense–think–act loop closes through the physical world?
   A) The motors are wired directly to the sensors
   B) The only link from action back to sensing is the world's physical response, so the robot must measure to know what happened
   C) The robot runs without any computer
   D) The loop only works outdoors

4. Which of these is a perception task rather than a control task?
   A) Choosing the motor voltage to hold a joint at 30°
   B) Deciding how hard to brake
   C) Sending a command to a motor driver
   D) Working out from a camera image where a cup is on the table

5. A robot's loop cannot be made any faster, but it is reacting too late. Which response is a sensible engineering choice?
   A) Increase its speed so it finishes sooner
   B) Ignore the latency because it is small
   C) Move more slowly or leave a larger safety margin
   D) Remove the sensors to save time


## 1.5 Robots, people and safety

*How engineers keep people safe around robots — hazards, guarding, collaborative operation and emergency stops — and the ethical questions raised by deciding where robots are used.* (about 30 min)

### A powerful machine that cannot see you

A typical industrial robot arm can swing a heavy load at speeds of several metres per second. It does exactly what its program says, and unless it has been specifically designed to notice people, it has no idea anyone is there. That combination — strong, fast and unaware — is why robot safety is taken so seriously. This lesson explains the main hazards, the layers of protection engineers use, and the wider questions of whether and how robots should be deployed.

### What can go wrong

Engineers start safety work with a **risk assessment**: listing what could cause harm, how likely it is, and how severe it would be. For robots, common hazards include:

- **Impact**: being struck by a moving arm, tool or carried object.
- **Crushing and trapping**: being caught between the robot and a fixed object, such as a wall, table or another machine. This is often more dangerous than a free impact, because the body cannot move away.
- **Unexpected motion**: a robot starting, restarting or moving in a way the person did not expect — for example after a program change or a fault.
- **The tool itself**: blades, welding arcs, lasers, hot surfaces or high-pressure air.
- **Stored energy**: a raised arm can fall if power is removed and its brakes fail; springs and compressed air can release suddenly.
- **Electrical hazards** from the robot's power systems.

A sobering lesson from industrial experience is that people are often at most risk not during normal operation but during **programming, maintenance and fault finding**, when they are close to the robot and its normal protections may be bypassed.

### Layers of protection

No single measure makes a robot safe. Engineers use several layers, and the general order of preference is well established in safety engineering:

1. **Eliminate or reduce the hazard by design.** Use a lighter, slower or rounder robot; reduce the force it can exert; remove sharp edges; avoid pinch points.
2. **Guarding and safeguarding.** Keep people out of the danger zone with fixed fences, or detect them with devices such as light curtains, pressure mats or laser area scanners that stop the robot when someone enters.
3. **Information and training.** Warning signs, clear procedures, and training so that people know how the system behaves.
4. **Personal protective equipment** such as safety glasses — the last line of defence, not the first.

Notice that the most effective measures are at the top: changing the machine works whether or not anyone remembers a rule.

### Emergency stops

An **emergency stop** (e-stop) is a control that anyone nearby can use to stop the machine quickly in a dangerous situation. Typical e-stops are a red mushroom-headed button on a yellow background, designed to be hit with the palm. Several design features matter:

- **Latching.** Once pressed, the button stays pressed. The robot must not restart just because the button is released; someone has to deliberately reset it, after checking it is safe.
- **Fail-safe wiring.** E-stop circuits are usually wired so that a *broken* wire or loose connector causes a stop, rather than silently disabling the button. The circuit must be actively complete for the robot to run.
- **Independence from software.** A well-designed e-stop removes power from the actuators through dedicated safety hardware, so it still works if the main computer has crashed.

There are different ways to stop. Cutting power instantly is simple, but a fast-moving heavy arm then coasts until its brakes catch. A **controlled stop** uses the motors to brake the arm along its path first, then removes power. Engineers choose the type based on the risk assessment. Remember also that an e-stop is a backup; it is not a substitute for guarding, because it depends on someone noticing danger and reacting in time.

### Collaborative robots

Traditionally, industrial robots work inside fences and people stay out. **Collaborative robots**, or **cobots**, are designed to share space with people. International standards for industrial robots (the ISO 10218 series, with detailed guidance on collaboration in ISO/TS 15066) describe several ways a robot and person can work together safely:

- **Safety-rated monitored stop**: the robot stops and stays stopped while a person is in the shared space.
- **Hand guiding**: a person moves the robot directly by hand, for example to teach it a path.
- **Speed and separation monitoring**: sensors track how close people are, and the robot slows down as they approach and stops before contact is possible.
- **Power and force limiting**: the robot is designed so that if contact happens, the forces and pressures stay below limits chosen to avoid injury.

A crucial point: **an application is collaborative, not just a robot.** A gentle cobot holding a sharp knife is not safe to work next to. The whole system — robot, tool, workpiece and task — must be assessed.

### Connecting safety to timing

The previous lesson showed that a robot moving at speed v travels about v · (T + L) before reacting. Speed and separation monitoring rests on exactly this idea. The robot must keep enough distance from a person to cover its own reaction time and its stopping distance, plus the distance the *person* might move in that time.

### Worked example

A person walks towards a robot at 1.6 m/s, a common assumption for walking speed in safety calculations. The robot's sensing and decision delay is 0.1 s, and it needs a further 0.3 s to come to a stop. During that 0.4 s:

```
person moves  = 1.6 m/s × 0.4 s = 0.64 m
```

If the robot is also moving towards the person at 0.5 m/s, it covers up to 0.5 × 0.4 = 0.2 m (an overestimate, since it slows during braking). The required separation is therefore at least about 0.64 + 0.2 = 0.84 m, before adding margins for sensor error. Halve the robot's speed and its share shrinks — one reason cobots often slow down when people come near.

This is a simplified version of the real calculations, which add terms for sensor uncertainty and intrusion distance, but the structure is the same.

> **If you build robots yourself.** Even small hobby robots can pinch fingers, tip over or overheat. Work with adult supervision, keep speeds and forces low while testing, keep hands and hair clear of moving parts, and always have an easy, obvious way to cut power that you have tested before you need it.

### The ethics of deploying robots

Safety engineering asks "how do we prevent harm from this robot?" Ethics asks wider questions as well: should this robot be used here at all, who benefits, and who bears the risks? These questions have no formula, but engineers are expected to think about them. Some recurring ones:

- **Work and livelihoods.** Robots can take over dangerous, dirty or dull jobs, which can protect workers. They can also change or remove jobs people depend on. How a deployment is planned — retraining, consultation, who shares the gains — matters.
- **Who is exposed to risk.** A delivery robot on a pavement shares space with people who never agreed to test it, including children and people using wheelchairs or canes.
- **Privacy.** Robots with cameras and microphones collect data about people around them. Who stores it, and for what?
- **Responsibility.** When an autonomous system makes a harmful decision, it should still be clear which people are accountable: designers, operators or owners. "The robot did it" is not an answer.
- **Honesty about capability.** Overstating what a robot can do — in sales material, in research or in a school project — leads people to trust it in situations where it will fail.

A good habit is to list the people affected by a robot, not just its users, and ask how each might be helped or harmed.

### Recap

- Start with a **risk assessment**; major hazards include impact, crushing, unexpected motion, the tool and stored energy.
- Prefer protection by **design**, then **guarding and detection**, then information, then protective equipment.
- **E-stops** latch, fail safe and work independently of software, but are a backup, not a substitute for guarding.
- **Collaborative** operation uses monitored stops, hand guiding, speed and separation monitoring, or power and force limiting — and it is the whole application that must be safe.
- Separation distances follow from reaction time and stopping time, connecting safety to the loop timing you have already studied.
- **Ethics** asks who benefits, who bears risk, and who is responsible.

#### Check your understanding

1. Why must an emergency stop button latch when pressed?
   A) So the robot cannot restart just because the button is released; someone must deliberately reset it
   B) So the button is easier to see
   C) So the robot can keep moving at a slower speed
   D) Because latching buttons use less power

2. Which protective measure is generally the most effective, according to the order of preference in safety engineering?
   A) Warning signs
   B) Safety glasses
   C) Reducing the hazard by design, such as limiting the robot's speed and force
   D) A training video

3. A power-and-force-limited cobot is fitted with a sharp cutting blade. What is the key safety point?
   A) The application is safe because the robot is a cobot
   B) Safety depends on the whole application, including the tool, so this must be reassessed
   C) Cobots cannot carry tools
   D) Only the robot's speed matters

4. A person approaches at 1.6 m/s. The robot needs 0.5 s in total to detect them and stop. How far can the person move in that time?
   A) 0.32 m
   B) 1.1 m
   C) 3.2 m
   D) 0.8 m

5. Why are e-stop circuits usually wired so that a broken wire causes a stop?
   A) So that a fault cannot silently disable the emergency stop
   B) To save copper
   C) So the robot runs faster
   D) Because software cannot read the button otherwise

**Go further:**

- Wikipedia — Cobot: https://en.wikipedia.org/wiki/Cobot — History and background on collaborative robots, with references to the relevant safety standards.


## 1.6 Reading a robot specification

*What the numbers on a robot spec sheet really mean — payload, reach, speed, accuracy, repeatability and resolution — and how to compare two robots fairly.* (about 30 min)

### Numbers you will meet again and again

Every robot arm, mobile robot and motor comes with a **specification sheet**: a page of numbers describing what it can do. Spec sheets are how engineers choose between machines without buying both. But they are easy to misread. A number can be correct and still mislead you if you do not know exactly what it measures or under which conditions it was measured. This lesson works through the most common specifications for a robot arm and shows how to compare two of them.

### Payload

**Payload** is the mass the robot can carry at its end effector while still meeting its other specifications. Three details catch people out:

- **The gripper counts.** If an arm has a 5 kg payload and the gripper weighs 1.2 kg, you can only pick up objects up to 3.8 kg.
- **Distance from the wrist matters.** Payload is usually rated with the load's centre of mass close to the wrist. A long tool that holds the load further out produces more torque on the wrist joints. Recall that torque is force times distance: the same mass twice as far out produces twice the torque. Spec sheets often include a chart of allowed payload versus offset.
- **Rated is not maximum.** The rated payload is what the robot can handle while keeping its speed and accuracy figures. It might move a heavier load slowly, but it is not designed to.

### Reach and workspace

**Reach** is usually the maximum distance from the robot's base axis to the wrist or tool flange. You met the idea of a workspace earlier: reach is its outer edge. But the tool adds length, joint limits cut out regions, and the edge of the workspace is a poor place to work, because the arm is nearly straight and has little ability to move or orient the tool there. A good rule is to keep important work comfortably inside the reach, not at its limit.

### Speed

Speed can be specified in several ways, and they are not interchangeable:

- **Joint speeds**, in degrees per second for each axis.
- **Maximum tool speed**, in metres per second.
- **Cycle time** for a standard pick-and-place motion.

Maximum speeds are reached only on long, free movements. Short moves spend most of their time accelerating and decelerating, so in practice the arm rarely reaches its top speed. Speed figures are also normally given with a light load, and collaborative operation may require much lower speeds near people.

### Accuracy, repeatability and resolution

These three are the most commonly confused specifications in robotics. Imagine sending the arm to the same target point many times and marking where the tool actually ends up.

- **Repeatability** describes how tightly those marks cluster together: how close the robot returns to the *same* place each time.
- **Accuracy** describes how close the *centre* of the cluster is to the target you asked for: whether the robot goes where you told it.
- **Resolution** is the smallest step the robot can command or detect, such as the smallest change an encoder can measure.

The classic picture is a dartboard. Darts tightly bunched in the corner are repeatable but not accurate. Darts scattered evenly around the bullseye are accurate on average but not repeatable. A good robot needs both, but for many factory tasks repeatability matters most: if a robot is *taught* a position by being moved there, it only needs to return to it reliably.

Industrial arms commonly have repeatability measured in hundredths of a millimetre, while their absolute accuracy can be several times, even ten or more times, worse unless they are carefully calibrated. That is why spec sheets often list repeatability prominently and accuracy rarely. Fine resolution does not guarantee either: an encoder can report tiny steps while slack in the gears lets the tool wander by much more.

### Computing accuracy and repeatability

Here is a simplified version of how these quantities are measured. (The standard method for industrial robots, defined in ISO 9283, uses statistics over many measurements; the idea is the same.) The numbers are made up for illustration.

```python
import math

# Made-up measurements for illustration: the arm was sent to the same
# target (x = 0, y = 0, in mm) five times and its tool position measured.
target = (0.0, 0.0)
visits = [(0.52, 0.31), (0.55, 0.28), (0.49, 0.30), (0.53, 0.33), (0.51, 0.28)]

mean_x = sum(x for x, y in visits) / len(visits)
mean_y = sum(y for x, y in visits) / len(visits)

accuracy = math.dist(target, (mean_x, mean_y))
spread = max(math.dist((mean_x, mean_y), p) for p in visits)

print(f"average position: ({mean_x:.3f}, {mean_y:.3f}) mm")
print(f"accuracy (target to average): {accuracy:.3f} mm")
print(f"repeatability (worst distance from average): {spread:.3f} mm")
```

Output:

```
average position: (0.520, 0.300) mm
accuracy (target to average): 0.600 mm
repeatability (worst distance from average): 0.036 mm
```

This robot returns to within about 0.04 mm of the same spot every time, but that spot is 0.6 mm from where it was told to go. It is very repeatable and much less accurate — exactly the pattern described above. Calibration could shift the cluster onto the target, because a consistent error can be measured and corrected; random scatter cannot.

### Comparing two spec sheets

Suppose you need an arm to move small parts, each 0.4 kg, from a tray into a fixture with holes that need ±0.1 mm placement. The tray is 550 mm from where the arm will be mounted. Your gripper weighs 0.6 kg. Two arms are available (made-up figures for illustration):

```
                     Arm A        Arm B
rated payload        3 kg         0.8 kg
reach                600 mm       900 mm
max tool speed       1.5 m/s      2.0 m/s
repeatability        ±0.05 mm     ±0.03 mm
mass                 15 kg        11 kg
```

Work through it requirement by requirement rather than looking for the biggest numbers:

1. **Payload.** Gripper plus part is 0.6 + 0.4 = 1.0 kg. Arm A's 3 kg leaves a healthy margin. Arm B's 0.8 kg is *exceeded*, so Arm B fails outright, however good its other numbers look.
2. **Reach.** The tray at 550 mm is inside both, but for Arm A it is close to the 600 mm edge, once the gripper length is accounted for. You might move the mounting point closer to the tray.
3. **Repeatability.** Both are well within ±0.1 mm. Because the fixture position can be taught, repeatability is the relevant number.
4. **Speed.** Neither speed is likely to matter for short moves; you would compare cycle times if throughput were critical.

Arm A is the sensible choice, with a note to check the reach geometry. Notice that Arm B "wins" on most of the rows and is still unusable. **One failed requirement outweighs any number of impressive figures.**

### Questions to ask of any specification

- Under what conditions was this measured: load, speed, temperature, position in the workspace?
- Is it a typical value or a guaranteed one?
- Does it apply to the joint, the wrist flange or the tool tip?
- Which specifications actually matter for *my* task?

### Recap

- **Payload** includes the gripper and depends on how far the load sits from the wrist.
- **Reach** is the outer edge of the workspace; keep important work well inside it.
- **Speed** figures are best-case; short moves rarely reach them.
- **Repeatability** is returning to the same place; **accuracy** is going to the commanded place; **resolution** is the smallest step. They are different, and repeatability is usually much better than accuracy.
- Compare robots requirement by requirement; a single failed requirement rules a robot out.

> **Specs are claims.** A spec sheet is a set of claims made under particular test conditions. Treat it the way you would treat any claim: check the conditions, and if a task depends critically on one number, test it yourself under your own conditions and record the result honestly — including if it falls short of the sheet.

#### Project: Paper project: be the judge

Invent a task for a robot arm — for example stacking cups, sorting coins, or placing labels on jars. Write down the payload (including a gripper you choose), the farthest point the arm must reach and the placement precision the task needs.

Then invent two arm spec sheets, written as lists or a code-block layout like the one in this lesson, designed so that the arm with the "better-looking" numbers fails one requirement.

Swap with a friend or family member if you can, and ask them to choose the right arm and explain why. Finally, write two questions you would ask a supplier about the conditions behind their figures.

**Deliverables**

- A task description with payload, reach and precision requirements
- Two invented spec sheets, labelled as made up
- A requirement-by-requirement comparison and choice
- Two questions about test conditions

#### Check your understanding

1. An arm is sent to the same point many times. Its tool lands in a tight cluster, but the cluster is 1 mm from the target. The arm is:
   A) Accurate but not repeatable
   B) Neither accurate nor repeatable
   C) Repeatable but not very accurate
   D) Both accurate and repeatable

2. An arm has a rated payload of 5 kg. Your gripper weighs 1.5 kg. What is the heaviest object it should be used to pick up?
   A) 6.5 kg
   B) 3.5 kg
   C) 5 kg
   D) 1.5 kg

3. Why might a robot with a very fine encoder resolution still have poor accuracy?
   A) Fine resolution always guarantees accuracy
   B) Encoders only work at low speeds
   C) Resolution is measured in kilograms
   D) Slack in gears, flexing links and calibration errors can move the tool by more than the encoder's smallest step

4. Arm X beats Arm Y on reach, speed and repeatability, but its payload is below what your task needs. What should you conclude?
   A) Arm X is unsuitable, because one failed requirement rules it out
   B) Arm X is better, because it wins on more rows
   C) Average the scores of the two arms
   D) Run Arm X a little faster to compensate

5. Why is a robot's maximum tool speed often not reached in practice?
   A) Speed specs are always false
   B) Short moves spend most of their time accelerating and decelerating
   C) Robots are not allowed to move quickly
   D) Speed is only measured when the robot is switched off


---

# Module 2: Robotic system architecture

How the parts of a robot — power, sensing, computing, actuation and software — are organized and connected so that the whole system works reliably.

**Objectives**

- Draw a block diagram of a robot showing power, sensing, computation and actuation.
- Explain the difference between low-level control loops and high-level planning.
- Describe how timing and communication between subsystems affect behaviour.
- Identify single points of failure in a simple robot design.


## 2.1 Subsystems of a robot

*Breaking a robot into mechanical, electrical, sensing, computing and software subsystems, and why the interfaces between them are where most problems hide.* (about 25 min)

### Too big to think about all at once

Even a small robot contains hundreds of decisions: which motor, which battery, which sensor, which connector, which line of code. Nobody can hold all of them in their head at the same time. Engineers cope by dividing a robot into **subsystems** — groups of parts that do one job together — and then thinking carefully about how those groups connect. This way of thinking is called **system architecture**, and it is the subject of this whole module.

A good architecture lets different people work on different parts at the same time, makes faults easier to find, and lets you replace one part without redesigning everything else.

### The five common subsystems

Most robots, from a classroom line-follower to an industrial arm, can be described with the same five subsystems.

**Mechanical.** The physical body: frame, links, joints, wheels, gears, bearings and the end effector. It carries loads, sets the robot's degrees of freedom and protects everything else. Its key numbers are masses, dimensions, stiffness and the torques it must transmit.

**Electrical.** Everything to do with power: the battery or power supply, voltage regulators, fuses, switches, wiring, and the **motor drivers** that turn small control signals into the large currents motors need. The emergency stop circuit usually lives here too.

**Sensing.** The sensors that measure the robot itself (joint encoders, motor current, battery voltage) and its surroundings (cameras, distance sensors, force sensors). Engineers sometimes call the first kind *proprioceptive* sensors and the second kind *exteroceptive* ones.

**Computing.** The processors that run the robot's software: often one or more small **microcontrollers** close to the hardware, and sometimes a more powerful computer for heavy tasks such as vision. A later lesson in this module looks at how work is split between them.

**Software.** The programs: drivers that talk to hardware, control loops, perception, planning and the user interface. Software is not a physical subsystem, but it has its own structure and its own interfaces, so it is treated as one.

Actuators — the motors and other devices that create motion — sit across the boundary between mechanical and electrical, which is a hint about where trouble starts.

### Interfaces: where subsystems meet

An **interface** is any point where two subsystems depend on each other. Every interface is an agreement, and every agreement can be broken. The main kinds are:

- **Mechanical interfaces**: mounting holes, shaft sizes, the space a part occupies. A motor that does not fit its bracket is an interface failure.
- **Electrical interfaces**: voltage levels, current limits and connectors. A sensor designed for 3.3 V logic connected to a 5 V signal may be damaged.
- **Data interfaces**: how information is sent — which wires, which protocol, which units, how often. A distance sent in millimetres but read as metres is an interface failure.
- **Software interfaces**: the functions and messages one program offers another, and what each one promises.

Interfaces are where most integration problems appear, because each side may be correct on its own and the system still fails when they are joined. A famous real example is NASA's Mars Climate Orbiter, lost in 1999 partly because one piece of software produced results in imperial units while another expected metric units.

Engineers protect interfaces by writing them down. A simple **interface list** records, for each connection, what flows across it, in which units, at what rate, and who is responsible for each side.

### Worked example: a line-following robot

A small two-wheeled robot follows a black line on white paper. Breaking it down:

- **Mechanical**: chassis plate, two wheels on gearmotors, a caster, a bracket holding sensors 5 mm above the floor.
- **Electrical**: a battery pack, a power switch, a fuse, a motor driver board, a voltage regulator making 5 V for the logic.
- **Sensing**: five infrared reflectance sensors in a row; a battery voltage measurement.
- **Computing**: one microcontroller.
- **Software**: sensor reading, line-position estimate, a steering controller, motor output.

Now list a few interfaces:

1. Sensor bracket to chassis (mechanical): sets sensor height. If it changes, the readings change.
2. Sensors to microcontroller (data): five analog voltages, read every 2 ms.
3. Microcontroller to motor driver (data and electrical): two speed signals and two direction signals at logic voltage.
4. Motor driver to battery (electrical): must handle the motors' peak current.
5. Line-position code to steering code (software): a number from −2 to +2, where 0 means centred.

Writing interface 5 down settles a question that could otherwise cause a bug: what *does* "+2" mean — line far left or far right?

### Single points of failure

A **single point of failure** is one part whose failure stops the whole system. In the line-follower, the battery, the fuse, the microcontroller and the motor driver are all single points of failure. That may be acceptable for a classroom robot. For a robot working near people or in a remote place, engineers look for single points of failure deliberately and ask: can this fail safely, can it be detected, or should it be duplicated?

### Recap

- Robots are commonly divided into **mechanical, electrical, sensing, computing and software** subsystems.
- **Interfaces** — mechanical, electrical, data and software — are agreements between subsystems, and most integration failures happen there.
- Write interfaces down: what crosses, in which units, how often, and who owns each side.
- Look for **single points of failure** and decide whether each is acceptable.

#### Project: Paper project: take a robot apart (on paper)

Choose a robot you know something about — a robot vacuum, a drone, a toy robot, or one of the robots from earlier lessons.

1. Draw five boxes, one per subsystem, and list the main parts in each. Guess where you are unsure, and mark guesses with a question mark.
2. Draw lines between boxes for at least **six** interfaces. Label each with what crosses it (force, power, data) and, where you can, units and rate.
3. Circle every single point of failure you can find, and for one of them, suggest how the robot could detect the failure or fail safely.

Paper and pencil are enough. Do not open up a real device to check.

**Deliverables**

- A five-box subsystem breakdown with parts listed
- At least six labelled interfaces
- Circled single points of failure, with one improvement suggested

#### Check your understanding

1. Which subsystem does a motor driver board belong to?
   A) Mechanical
   B) Electrical
   C) Software
   D) Sensing

2. One team's code sends a distance in millimetres; another team's code reads it as metres. What kind of failure is this?
   A) A mechanical failure
   B) A sensor failure
   C) A data interface failure
   D) A power failure

3. What is a single point of failure?
   A) A part whose failure stops the whole system
   B) The first part to fail in testing
   C) A part that is never used
   D) A sensor with only one reading

4. A joint encoder measures the robot's own arm angle. A camera measures the room. How are these sensors sometimes classified?
   A) Both are exteroceptive
   B) Both are actuators
   C) The camera is proprioceptive and the encoder is exteroceptive
   D) The encoder is proprioceptive and the camera is exteroceptive

**Go further:**

- Wikipedia — Block diagram: https://en.wikipedia.org/wiki/Block_diagram — A short introduction to the box-and-line diagrams engineers use to show subsystems and their connections.


## 2.2 Power systems and energy budgets

*Voltage rails, current draw, the difference between peak and average power, and how to estimate how long a robot will run on its battery.* (about 35 min)

### The question every mobile robot faces

"How long will it run?" is one of the first questions anyone asks about a mobile robot, and one of the easiest to get wrong. A robot that runs out of energy in the middle of a task, or whose computer resets every time the motors start, has a power problem, not a software problem. This lesson shows how to estimate a robot's power needs on paper before anything is built.

### A few quantities

You may know some of these already; the embedded systems pathway covers them in more depth.

- **Voltage** (V, volts) is the electrical "push".
- **Current** (I, amperes or amps) is the rate at which charge flows.
- **Power** (P, watts) is the rate at which energy is used: P = V × I.
- **Energy** (watt-hours, Wh) is power multiplied by time. One watt for one hour is 1 Wh.

Battery capacity is often given in **amp-hours** (Ah) or milliamp-hours (mAh). To get energy, multiply by the battery's voltage: a 12 V, 6 Ah battery stores about 12 × 6 = 72 Wh. Comparing batteries in watt-hours avoids confusion when their voltages differ.

### Voltage rails

Different parts of a robot want different voltages. Motors might run from 12 V, a small computer from 5 V, and a microcontroller and its sensors from 3.3 V. Each of these supplies is called a **rail**. The battery feeds the highest rail directly, and **voltage regulators** produce the lower ones.

Regulators are not free:

- A **linear regulator** drops the extra voltage as heat. Its input current roughly equals its output current, so converting 5 V to 3.3 V at 0.15 A draws 5 × 0.15 = 0.75 W from the 5 V rail to deliver 3.3 × 0.15 ≈ 0.5 W. The other quarter of a watt becomes heat. Linear regulators are simple and quiet electrically, and fine for small currents.
- A **switching regulator** converts voltage much more efficiently, often around 85–95%, by switching current on and off rapidly. Larger loads, like a single-board computer, normally use one.

### Peak versus average

Robots do not draw a steady current. A motor starting from rest, or pushing against an obstacle, can draw several times its normal running current for a moment. A computer draws more while processing images than while idle.

Two different questions follow:

- **Average power** decides **run time**: how quickly the battery's energy is used up.
- **Peak current** decides whether the **battery, wiring, fuses and regulators** can cope at the worst moment. If the battery voltage sags too far during a motor surge, a regulator can drop out and the computer may reset — a classic and confusing fault.

A useful habit is to list every load with both an average and a peak figure.

### Worked example: an energy budget

Here is a budget for a small two-wheeled robot with a single-board computer and camera. The numbers are made up for illustration, but are of a realistic size.

- Battery: 12 V, 6 Ah. We plan to use only 80% of its energy, to protect it and leave a reserve.
- Two drive motors on 12 V: 0.8 A each on average while driving, up to 3 A each at peak. The robot drives 60% of the time.
- On the 5 V rail, from a 90%-efficient switching regulator: a computer (1.5 A average, 2.5 A peak), a camera (0.3 A) and a linear 3.3 V regulator for the microcontroller and sensors (0.15 A).

```python
# Energy budget for a small two-wheeled robot (illustrative numbers).
BATTERY_V = 12.0
BATTERY_AH = 6.0
USABLE = 0.8              # plan to use only 80% of the stored energy
REG_EFFICIENCY = 0.9      # 12 V -> 5 V switching regulator

# Loads on the 5 V rail: (name, average amps, peak amps)
rail_5v = [
    ("single-board computer", 1.50, 2.50),
    ("camera", 0.30, 0.30),
    ("3.3 V linear regulator for MCU + sensors", 0.15, 0.15),
]
# Each drive motor runs straight from 12 V.
MOTOR_AVG_A, MOTOR_PEAK_A, MOTORS, DRIVING_FRACTION = 0.8, 3.0, 2, 0.6

p5_avg = 5.0 * sum(avg for _, avg, _ in rail_5v)
p5_peak = 5.0 * sum(peak for _, _, peak in rail_5v)
p_motors_avg = MOTORS * BATTERY_V * MOTOR_AVG_A * DRIVING_FRACTION

p_avg = p_motors_avg + p5_avg / REG_EFFICIENCY
i_peak = MOTORS * MOTOR_PEAK_A + (p5_peak / REG_EFFICIENCY) / BATTERY_V

energy_wh = BATTERY_V * BATTERY_AH * USABLE
print(f"5 V rail average: {p5_avg:.2f} W (draws {p5_avg / REG_EFFICIENCY:.2f} W from the battery)")
print(f"motors average:   {p_motors_avg:.2f} W")
print(f"total average:    {p_avg:.2f} W = {p_avg / BATTERY_V:.2f} A at {BATTERY_V:.0f} V")
print(f"worst-case peak:  {i_peak:.2f} A")
print(f"usable energy:    {energy_wh:.1f} Wh -> run time {energy_wh / p_avg:.2f} h")
```

Output:

```
5 V rail average: 9.75 W (draws 10.83 W from the battery)
motors average:   11.52 W
total average:    22.35 W = 1.86 A at 12 V
worst-case peak:  7.37 A
usable energy:    57.6 Wh -> run time 2.58 h
```

Reading the results:

- The estimated run time is about **2.6 hours**, or roughly 2 hours 35 minutes.
- The computer and camera use almost as much energy as the motors. On many small robots, computing is a large share of the budget — a surprise to people who assume motors dominate.
- The peak current of about **7.4 A** is four times the average. The battery, wiring, switch and fuse must all be rated for it, even though the robot rarely draws it.

### Making the estimate honest

A budget is only as good as its assumptions. Good practice is to:

- **State each assumption** (driving 60% of the time, 80% usable energy) so others can check it.
- **Add margin.** Real batteries deliver less energy when cold, old or discharged quickly. Many engineers plan for 20–30% less run time than the calculation gives.
- **Measure and update.** Once a prototype exists, measure the actual current and correct the budget.

### Recap

- P = V × I; energy in Wh = power × hours; battery energy ≈ voltage × amp-hours.
- Robots use several **voltage rails**; linear regulators waste the voltage difference as heat, switching regulators are more efficient.
- **Average** power sets run time; **peak** current sets what the battery, wiring and fuses must survive.
- An energy budget lists every load with average and peak values, states assumptions and includes margin.

> **Batteries store a lot of energy.** Rechargeable lithium batteries can overheat or catch fire if short-circuited, punctured, overcharged or crushed. If you ever work with real robot batteries, do so with adult supervision, use the correct charger, include a fuse close to the battery, and never leave a battery charging unattended. The calculations in this lesson need no hardware at all.

#### Project: Paper or Python project: budget your own robot

Design, on paper, a power budget for a robot of your choice — for example a garden-watering robot or a small delivery robot.

1. List every load with its rail voltage, average current, peak current and the fraction of time it is on. Use made-up but realistic numbers and label them as such.
2. Choose a battery voltage and capacity. Calculate the average power, the peak current and the estimated run time, by hand or by adapting the Python program above.
3. Change one design decision — a bigger battery, a more efficient regulator, or a computer that sleeps when idle — and recalculate. Which change helped most?

This is a calculation exercise only; do not connect any real batteries or motors.

**Deliverables**

- A load list with average and peak currents and duty fractions
- Calculated average power, peak current and run time
- One design change and its effect on run time

**Safety (adult supervision required):** This project is calculation only. If you later build anything, do so only under adult supervision, at low voltage, with a fuse near the battery and the manufacturer's charger, and never leave batteries charging unattended.

#### Check your understanding

1. About how much energy does a 7.2 V, 5 Ah battery store?
   A) 1.44 Wh
   B) 12.2 Wh
   C) 36 Wh
   D) 72 Wh

2. A robot uses 18 W on average and has 54 Wh of usable energy. What is its estimated run time?
   A) 3 hours
   B) 0.33 hours
   C) 72 hours
   D) 36 hours

3. Every time its motors start, a robot's computer resets. Which quantity most likely needs attention?
   A) The average power
   B) The peak current and the resulting voltage sag
   C) The camera resolution
   D) The robot's top speed

4. A linear regulator supplies 0.2 A at 3.3 V from a 5 V input. Roughly how much power does it waste as heat?
   A) 0.66 W
   B) 1.0 W
   C) 0.2 W
   D) 0.34 W

5. Why do engineers usually plan to use only part of a battery's rated energy?
   A) Batteries only work when half full
   B) To leave a reserve and allow for cold, ageing and fast discharge, which all reduce the energy available
   C) Because rated capacity is always printed incorrectly
   D) To make the robot heavier


## 2.3 Computation on a robot

*Microcontrollers versus single-board computers, what real-time really means, and how robots split their work between different processors.* (about 25 min)

### Two very different kinds of computer

Open up many modern robots and you will find not one computer but several. A small chip near each motor, another reading sensors, and perhaps a larger board running vision software. Why not use one powerful computer for everything? The answer comes down to a property that ordinary computing rarely worries about: doing things **on time**, every time.

### Microcontrollers

A **microcontroller** (MCU) is a complete small computer on a single chip: processor, memory for the program (flash), working memory (RAM), and built-in **peripherals** such as timers, analog-to-digital converters and serial ports. Typical microcontrollers run at tens to hundreds of megahertz with kilobytes to a few megabytes of memory. They usually run a single program directly on the hardware, with no full operating system, or a small **real-time operating system** (RTOS).

Their strengths:

- **Predictable timing.** With nothing else competing for the processor, a task that takes 50 µs takes 50 µs every time.
- **Direct hardware access.** Pins, timers and converters are right there, so the MCU can read an encoder or generate a motor signal with very little delay.
- **Low power and fast start-up.** Many draw well under a watt and start running within milliseconds of power-on.

### Single-board computers

A **single-board computer** (SBC) is a small but complete general-purpose computer: a processor running at around a gigahertz or more, often with several cores, gigabytes of RAM, storage, USB, networking and often a graphics processor. It usually runs a full operating system such as Linux.

Its strengths are the mirror image of the MCU's:

- **Lots of computing power** for cameras, maps, path planning and machine learning.
- **A rich software ecosystem**: libraries, networking, file systems and familiar programming languages.

Its weakness is timing. A general-purpose operating system juggles many tasks and decides for itself when your program runs. Most of the time a loop scheduled for every 1 ms runs close to every 1 ms, but occasionally it might be delayed by several milliseconds while the system does something else. This variation is called **jitter**. It also takes far longer to boot and draws several watts — as you saw in the energy budget lesson.

### What "real-time" means

In everyday speech "real-time" means "fast". In engineering it means something more precise: **a result is only correct if it arrives before its deadline.**

- In a **hard real-time** task, missing a deadline counts as a failure. A motor current loop or an airbag controller is hard real-time.
- In a **soft real-time** task, an occasional late result is undesirable but tolerable. Displaying video to an operator is soft real-time: a dropped frame is annoying, not dangerous.

Real-time is about **guarantees**, not raw speed. A gigahertz processor that is usually quick but sometimes 10 ms late is worse for a 1 kHz motor loop than a 100 MHz microcontroller that is never late.

### Worked example: a timing budget

A joint controller must run at 1 kHz, so it has a deadline every 1 ms = 1000 µs. On an MCU, measurements show the work takes:

```
read encoder              20 µs
compute control law       60 µs
update motor signal       10 µs
check safety limits       30 µs
total                    120 µs  of a 1000 µs period
```

That uses 12% of each period, leaving plenty of slack for other work. Engineers typically want comfortable headroom so that the loop keeps its deadline even on the worst pass, not just the average one. Now imagine running the same loop on an SBC with occasional 5 ms delays: it would miss several deadlines in a row, and the joint would briefly be uncontrolled.

### Splitting the work

Many robots therefore use both kinds of processor, each doing what it is good at:

- The **MCU** handles fast, time-critical, hardware-close work: motor control loops, encoder reading, safety limits, and a watchdog that stops the motors if commands stop arriving.
- The **SBC** handles heavy, less time-critical work: camera processing, mapping, planning and communication with people.
- They exchange messages, usually over a serial link, USB, CAN bus or Ethernet. The SBC sends goals such as "move joint 2 to 40°" or "drive at 0.3 m/s"; the MCU sends back measurements and status.

This split has a safety benefit. If the SBC crashes or freezes, the MCU notices that commands have stopped and brings the motors to a safe stop on its own. The time-critical part does not depend on the part most likely to misbehave.

There are other options: some robots use many MCUs, one per joint; some use processors with special hardware for neural networks; some use FPGAs, chips whose logic can be configured for very fast, parallel processing. The principle stays the same: put each job where its timing and computing needs are met.

### Recap

- **Microcontrollers** are small, predictable, low-power and close to the hardware.
- **Single-board computers** are powerful and flexible but have timing **jitter** and use more power.
- **Real-time** means meeting deadlines reliably; hard real-time deadlines must never be missed.
- A **timing budget** checks that each loop's worst-case work fits inside its period with headroom.
- Robots commonly split work: MCU for fast control and safety, SBC for perception and planning, connected by messages.

> **Average is not enough.** When you time a loop, record the **longest** pass you observe, not just the average. A loop that averages 200 µs but occasionally takes 1500 µs will miss a 1 ms deadline, and the average will never tell you.

#### Check your understanding

1. Which job is best suited to a microcontroller rather than a single-board computer?
   A) Running a 1 kHz motor current loop
   B) Finding objects in camera images
   C) Building a map of a building
   D) Hosting a web page for an operator

2. In engineering, what does real-time mean?
   A) As fast as possible
   B) Running on a gigahertz processor
   C) Producing a correct result before a deadline, reliably
   D) Showing results on a screen

3. A loop must run every 2 ms and its work takes 300 µs. What fraction of each period does it use?
   A) 6%
   B) 30%
   C) 67%
   D) 15%

4. Why is it useful for the microcontroller to stop the motors if commands from the single-board computer stop arriving?
   A) It saves memory
   B) It means a crash or freeze on the more complex computer leads to a safe stop instead of uncontrolled motion
   C) It makes the camera faster
   D) It is required for the robot to boot

5. What is jitter?
   A) Variation in when a task actually runs compared with when it was scheduled
   B) Electrical noise on a sensor wire
   C) The vibration of a motor
   D) A type of operating system

**Go further:**

- Wikipedia — Real-time computing: https://en.wikipedia.org/wiki/Real-time_computing — Hard, firm and soft real-time systems, deadlines and real-time operating systems.


## 2.4 Software layers, loops and timing

*How robot software is organised in layers — drivers, control, estimation and planning — why each layer runs at its own rate, and how latency builds up through the stack.* (about 30 min)

### One program, many speeds

A robot arm's motor needs a new command about a thousand times a second. Its route around an obstacle might only need updating a few times a second. Its overall task — "pack these ten items" — changes once every few minutes. If you tried to write all of this as one loop running at one speed, you would either waste enormous effort replanning a thousand times a second or control the motors far too slowly. Robot software solves this with **layers**, each running at the rate its job needs.

### The layers

From the bottom up, a typical robot's software looks like this:

**Drivers (hardware abstraction).** The lowest layer talks directly to hardware: reading an encoder count, sending a motor signal, receiving a camera frame. It converts raw hardware values into sensible units — counts into radians, raw readings into millimetres — so the layers above never need to know the details of a particular chip. If you swap a sensor for a different model, ideally only its driver changes.

**Control.** Control loops compare a target (where a joint should be, how fast a wheel should turn) with a measurement and compute the actuator command, as you saw in the feedback control module. They run fast and must be predictable.

**Estimation (state estimation).** This layer combines sensor readings to work out the robot's state: where it is, how fast it is moving, where objects are. It may merge wheel encoders with a motion sensor, or turn camera images into object positions.

**Planning.** Planners decide *what the robot should do next* to reach a goal: a path through a room, a sequence of arm positions to pick up a cup. They produce targets for the control layer.

**Task or behaviour layer.** At the top sits the logic of the job itself: which item to pick next, what to do if a grasp fails, when to ask a person for help.

Information flows **up** as measurements become estimates, and **down** as goals become plans, plans become targets and targets become motor commands.

### Why each layer has its own rate

Each loop should run fast enough for the thing it controls, and no faster. Typical orders of magnitude for a robot arm or mobile robot are:

```
motor current control      10 000 – 20 000 Hz
joint position/velocity      500 –  2 000 Hz
state estimation              50 –  1 000 Hz
camera perception             10 –     60 Hz
motion planning                1 –     10 Hz
task logic                 event-driven, as needed
```

These are rough ranges, not rules, but the pattern is important: **lower layers are faster**. Electrical current in a motor changes in microseconds; a joint's position changes in milliseconds; the robot's surroundings change over seconds. A loop must be several times faster than the changes it is trying to control.

A neat way to run several rates on one processor is to use one fast timer and run each task every N ticks. The program below simulates one second of a 1 ms tick driving three loops.

```python
# One 1 ms timer tick drives three loops at different rates.
PERIODS_MS = {"control": 1, "estimate": 10, "plan": 100}
runs = {name: 0 for name in PERIODS_MS}

for tick in range(1000):                 # one simulated second
    due = [name for name, period in PERIODS_MS.items() if tick % period == 0]
    for name in due:
        runs[name] += 1
    if tick in (0, 1, 10, 100):
        print(f"t = {tick:3d} ms: {', '.join(due)}")

for name, count in runs.items():
    print(f"{name:8s} ran {count:4d} times -> {count} Hz")
```

Output:

```
t =   0 ms: control, estimate, plan
t =   1 ms: control
t =  10 ms: control, estimate
t = 100 ms: control, estimate, plan
control  ran 1000 times -> 1000 Hz
estimate ran  100 times -> 100 Hz
plan     ran   10 times -> 10 Hz
```

Notice the ticks where several tasks are due at once, such as t = 0 and t = 100 ms. If planning takes 30 ms of processor time, it would push the control loop past its deadline on those ticks. Real systems avoid this by giving the fast loop priority — for example running it from a timer interrupt — or by putting slow tasks on a different processor, as discussed in the previous lesson.

### Latency adds up through the layers

When something changes in the world, the information has to climb up the stack and the response has to come back down. Each step adds delay. Suppose a mobile robot sees a box fall into its path:

```
camera exposure and transfer        30 ms
object detection                    40 ms
wait for next planning cycle     up to 100 ms  (planner runs at 10 Hz)
planning computation                20 ms
wait for next control cycle      up to   1 ms
motor responds                      50 ms
worst-case total               about  241 ms
```

At 1 m/s the robot travels about 24 cm before it even begins to react. Notice which items dominate. Waiting for the next planning cycle can cost as much as all the computation put together. This is why safety-critical reactions are often handled **low in the stack**: a bumper or distance sensor wired to the control layer can stop the motors within a few milliseconds, without waiting for vision and planning to catch up.

### Good layering habits

- **Each layer talks mainly to its neighbours.** The planner sends targets to control; it does not drive motors directly.
- **Use units, not raw values, above the driver layer.**
- **Decide what happens when data is late.** If the planner stops sending targets, the controller should hold position or stop safely, not keep chasing an old target forever.
- **Measure real timing.** Log when each loop actually runs and how long it takes.

### Recap

- Robot software is layered: **drivers, control, estimation, planning and task logic**.
- Lower layers run **faster**, because they control faster-changing quantities.
- A single fast tick can schedule several rates, but slow tasks must not delay fast ones.
- **Latency accumulates** through the stack, and waiting for slow loops can dominate.
- Put urgent, safety-relevant reactions low in the stack.

> **Rates are a design choice.** There is no law that says a planner must run at 10 Hz. Engineers choose each rate from how fast the world changes, how long the computation takes and what the processor can afford — and then check the choice by measuring the real system.

#### Check your understanding

1. Which software layer converts raw encoder counts into an angle in radians?
   A) Planning
   B) Task logic
   C) Estimation
   D) Drivers

2. Why do lower layers typically run at higher rates than upper layers?
   A) They control quantities that change faster, such as motor current and joint position
   B) Lower layers have less code
   C) Upper layers are less important
   D) Processors run faster at the bottom of the stack

3. With a 1 ms tick, a task that runs every 20 ticks has what rate?
   A) 20 Hz
   B) 50 Hz
   C) 200 Hz
   D) 1000 Hz

4. A planner runs at 5 Hz. In the worst case, how long might new information wait before the planner next uses it?
   A) 5 ms
   B) 20 ms
   C) 200 ms
   D) 5 s

5. Why is a bumper often connected to the control layer rather than handled by the planner?
   A) Planners cannot read sensors
   B) Bumpers produce too much data for the planner
   C) It makes the robot cheaper
   D) Handling it low in the stack avoids waiting for perception and planning, so the robot can stop within milliseconds


## 2.5 Communication inside a robot

*How the parts of a robot exchange information: buses, messages, publish/subscribe and request/response, and why every message should carry a timestamp.* (about 30 min)

### Parts that need to talk

The previous lessons split a robot into subsystems, processors and software layers. All of those pieces need to exchange information: the camera needs to tell the planner what it sees, the planner needs to tell the controller where to go, and the controller needs to report back how things are going. How that communication is organised affects how fast the robot reacts, how easy it is to change, and how it behaves when something goes wrong.

### Physical links: buses

At the hardware level, information travels over wires using agreed rules called **protocols**. A **bus** is a link that several devices share. The embedded systems pathway covers these in depth; here is the map:

- **UART serial**: a simple link between two devices, common between a microcontroller and a computer.
- **I2C**: a slow, two-wire bus where one controller talks to many small chips, such as sensors, each with its own address.
- **SPI**: a faster bus for short distances, often used for chips that produce lots of data.
- **CAN bus**: a robust bus designed for vehicles, good at carrying short messages between many motor controllers and sensors in an electrically noisy environment, with built-in priorities and error checking.
- **USB and Ethernet**: high-bandwidth links for cameras and between computers.

Choosing between them is a matter of distance, speed, number of devices, electrical noise and how reliably messages must arrive.

### Messages

On top of the wires, software exchanges **messages**: structured pieces of data with a defined meaning. A joint state message might contain the joint names, their angles in radians, their speeds in radians per second, and the time the measurement was taken. Defining messages carefully — fields, units, coordinate frames — is the data interface agreement from the first lesson in this module, written precisely enough for a computer.

### Two patterns: request/response and publish/subscribe

There are two common ways for software parts to exchange messages.

**Request/response.** One part asks a question and waits for an answer: "What is the battery level?" → "11.8 V". This is natural for occasional queries and one-off commands, but the asker must know who to ask, and it may sit waiting if the answer is slow.

**Publish/subscribe** (often shortened to pub/sub). A part that produces data **publishes** messages on a named channel, often called a **topic**, such as `/camera/image` or `/joint_states`. Any part interested in that data **subscribes** to the topic and receives every message published there. The publisher does not need to know who is listening, or how many listeners there are.

Pub/sub suits robots well, because so much robot data is a **stream**: sensor readings arriving at a steady rate, used by several consumers at once. The camera publishes images; the object detector, a logger and an operator display all subscribe. Adding a new consumer requires no change to the camera code. The widely used ROS framework (Robot Operating System) is built largely around this pattern.

Pub/sub has costs too. Because publishers do not know their subscribers, nobody automatically notices if a subscriber stops receiving messages, or if a publisher stops sending. Robust systems therefore watch for **missing or stale data** and react, for example by stopping safely if motor commands stop arriving.

### Why timestamps matter

Every measurement describes the world at a particular moment, and messages take time to travel. A camera image might be captured, compressed, sent, received and processed before anyone uses it, by which time the robot has moved on. If the software assumes data describes the world *now*, it will make errors that grow with speed and delay.

The cure is to **stamp each message with the time its measurement was taken**, not the time it arrived. With timestamps, software can line up data from different sensors correctly, discard data that is too old, and measure the system's actual latency.

### Worked example: matching an image to the arm's position

An arm moves its gripper steadily along x at 0.2 m/s and logs its position every 10 ms. A camera captures an image at t = 1234 ms, but processing means the planner only receives it at t = 1300 ms. To work out where the gripper was *in the picture*, the planner must use the arm's position at the capture time, interpolating between log entries. The data below is made up for illustration.

```python
# Made-up data for illustration. The arm logs its gripper x position
# every 10 ms. A camera image was captured at t = 1234 ms but only
# reached the planner at t = 1300 ms.
arm_log = [(1220 + 10 * i, 412.0 + 2.0 * i) for i in range(9)]  # (ms, mm)

def x_at(t):
    """Linearly interpolate the arm's logged position at time t (ms)."""
    for (t0, x0), (t1, x1) in zip(arm_log, arm_log[1:]):
        if t0 <= t <= t1:
            return x0 + (x1 - x0) * (t - t0) / (t1 - t0)
    raise ValueError("time outside the log")

captured, arrived = 1234, 1300
print(f"gripper x when the image arrived:  {x_at(arrived):.1f} mm")
print(f"gripper x when the image was taken: {x_at(captured):.1f} mm")
print(f"error if we ignore the timestamp:   {x_at(arrived) - x_at(captured):.1f} mm")
```

Output:

```
gripper x when the image arrived:  428.0 mm
gripper x when the image was taken: 414.8 mm
error if we ignore the timestamp:   13.2 mm
```

A 66 ms delay at 0.2 m/s gives 0.2 × 0.066 = 0.0132 m, matching the program. Ignoring the timestamp would place an object seen next to the gripper 13 mm away from where it really was — easily enough to miss a grasp.

### Clocks must agree

Timestamps only help if all parts of the robot agree on the time. Every processor has its own clock, and clocks **drift** apart slowly. Robots with several computers therefore **synchronise** their clocks, often with a network time protocol, or have one device timestamp everything on arrival and correct for known delays. The embedded systems pathway returns to this problem in detail.

### Recap

- Physical **buses** (UART, I2C, SPI, CAN, USB, Ethernet) carry data; the choice depends on speed, distance, noise and number of devices.
- **Messages** are precisely defined data, including units and frames.
- **Request/response** suits occasional queries; **publish/subscribe** suits streams with many consumers.
- Watch for **missing or stale data** and fail safely.
- **Timestamp** measurements when they are taken, and keep clocks synchronised, so data from different sources can be matched correctly.

> **Log everything with timestamps.** When a robot misbehaves, a log of timestamped messages is often the only way to reconstruct what happened. Recording data with timestamps from the start makes debugging far easier — and makes any results you report checkable by others.

#### Check your understanding

1. In publish/subscribe, what does a publisher need to know about its subscribers?
   A) Their exact number
   B) Their network addresses
   C) Nothing; it publishes on a topic and any subscriber receives the messages
   D) Which processor each one runs on

2. Which pattern is the most natural fit for asking a battery monitor for its current reading once?
   A) Request/response
   B) Publish/subscribe
   C) Broadcasting a video stream
   D) Clock synchronisation

3. An object moves at 0.5 m/s. An image of it reaches the planner 80 ms after capture. If the timestamp is ignored, how large is the position error?
   A) 4 mm
   B) 40 cm
   C) 0.4 mm
   D) 4 cm

4. Which time should a sensor message's timestamp record?
   A) When the message arrived
   B) When the measurement was taken
   C) When the robot was switched on
   D) When the message will be used

5. Why do robots with several computers need to synchronise their clocks?
   A) Clocks drift apart, so timestamps from different computers would not be comparable
   B) To make the processors run faster
   C) Because publish/subscribe needs no timestamps
   D) To save battery energy

**Go further:**

- Wikipedia — Publish–subscribe pattern: https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern — The general software pattern behind topics, with its advantages and drawbacks.


## 2.6 Drawing a system block diagram

*A worked case study: drawing the block diagram for a conceptual two-arm cooperative platform that combines vision with gripper force sensing. A proposed design only, with no results.* (about 35 min)

### A picture of the whole system

All through this module you have looked at pieces of a robot: subsystems, power rails, processors, software layers and messages. A **system block diagram** puts them on one page. Each block is a component or subsystem; each line is an interface, labelled with what flows across it. A good block diagram lets someone understand the whole robot in a few minutes, and it is often the first thing engineers draw when starting a design — long before any part is ordered.

This lesson draws one step by step for a robot that has not been built: a **conceptual two-arm cooperative platform**.

### Conventions

There is no single universal standard for robot block diagrams, but useful conventions are:

- **Blocks** are boxes with short names. Group related blocks inside a larger box for each subsystem.
- **Lines** are interfaces. Draw different kinds differently — for example solid for data, double for power, dashed for mechanical — and include a key.
- **Arrows** show the direction information or power flows.
- **Labels** say what crosses: the message, its rate, the voltage or the bus.
- **One level of detail at a time.** A top-level diagram might show ten to twenty blocks; details go on separate diagrams.

### The case study

Here is the design question. Robots find floppy materials such as cloth or cable hard to handle, because the shape keeps changing and the material often hides part of itself from the camera. Tactiverge's proposed Project TV-01 asks: *"Can inexpensive local force sensing compensate for intermittent visual information and improve cooperative robotic manipulation of unfamiliar deformable materials?"*

That question is a **proposed study with no results**. We are using it only as a realistic source of requirements for a design exercise. A platform to explore the question might need:

1. Two arms that can hold one piece of material together.
2. A camera viewing the workspace, which will sometimes be blocked.
3. A force sensor in each gripper, measuring how hard the material is being pulled or squeezed.
4. Software that combines vision and force, and keeps working sensibly when vision drops out.
5. An emergency stop that halts both arms, independent of software.
6. Logs of every sensor stream with timestamps, so that any future experiment could be checked.

> **A proposed design, not a result.** Everything in this case study is a conceptual design for teaching. No such platform is claimed to exist, and nothing here is evidence about whether force sensing helps. The rates and voltages below are typical illustrative choices, not measurements.

### Step 1: list the blocks

Start with the subsystems from the first lesson of this module and fill in components:

- **Mechanical**: left arm, right arm, two grippers, a table and camera mount.
- **Sensing**: one overhead camera; a force sensor in each gripper; joint encoders in each arm.
- **Computing**: one microcontroller per arm for joint control; one microcontroller reading both force sensors; one single-board computer for vision, fusion and planning.
- **Electrical**: power supply, arm power rail, logic power rail, e-stop circuit.
- **Software**: drivers, joint control, force reading, vision, a fusion layer, a planner, a logger.

### Step 2: draw the data paths

Place sensing on the left, decisions in the middle and actuation on the right, so the diagram reads like the sense–think–act loop:

```
                         [ Overhead camera ]
                                 | images, 30 Hz, USB
                                 v
 [ Force MCU ] --forces, 500 Hz--> [ Single-board computer          ]
   ^       ^      serial link      [  vision -> fusion -> planner   ]
   |       |                       [  logger (all timestamped)      ]
 [F-L]   [F-R]                         |                    |
 left    right                  joint targets 100 Hz   joint targets 100 Hz
 gripper gripper                       v   CAN bus          v
 force   force                  [ Left arm MCU ]      [ Right arm MCU ]
                                 1 kHz joint loop      1 kHz joint loop
                                    |      ^              |      ^
                                    v      | encoders     v      | encoders
                                [ Left arm motors ]   [ Right arm motors ]
```

Read it as a loop. The camera and force sensors measure; the single-board computer fuses the data and plans; joint targets go down to each arm's controller; the motors move the arms, which move the material, which changes what the camera sees and what the force sensors feel. The loop closes through the material itself.

Notice the rates, which follow the layering lesson: 1 kHz joint loops on microcontrollers at the bottom, 500 Hz force sensing, 100 Hz targets and 30 Hz vision above. Notice also that force readings travel on their own link rather than waiting for vision. When the camera's view is blocked, force data keeps arriving.

### Step 3: draw the power paths

Power gets its own diagram so the data diagram stays readable:

```
[ Mains power supply ] ==> [ E-stop safety relay ] ==> arm power rail ==> [ Arm motor drivers ]
          ||
          ++==> logic rail (5 V / 3.3 V) ==> [ MCUs, sensors, camera, computer ]

E-stop buttons (latching, fail-safe loop) --> safety relay: opens arm power rail only
```

The key architectural choice is visible at once: the e-stop removes power from the **motors** through dedicated hardware but leaves the **logic** powered. The computers keep running and logging, so engineers can see what happened, while the arms cannot move. This also means the e-stop works even if the software has crashed.

### Step 4: label the interfaces

Write an interface list to go with the diagram. A few entries:

- **Camera → computer**: images, 30 Hz, USB, each stamped with capture time.
- **Force MCU → computer**: two force values in newtons per message, 500 Hz, serial, stamped with measurement time.
- **Computer → arm MCUs**: joint angle targets in radians, 100 Hz, CAN bus. If no target arrives for 50 ms, the arm MCU holds position; if none for 200 ms, it stops.
- **Gripper → force sensor** (mechanical): the sensor must carry the full grip load without being overloaded.

### Step 5: hunt for weaknesses

A block diagram is a tool for asking hard questions:

- **Single points of failure.** The single-board computer is one: if it freezes, both arms lose their targets. The timeout rule in the interface list makes that failure safe, though not harmless to the task.
- **Shared clocks.** Data comes from four processors. Without clock synchronisation, the logs could not be lined up, and "the force rose just as the camera lost sight" would be unprovable.
- **The two arms pulling against each other.** Both arms hold one object, so position errors become forces in the material. Here the force sensors do double duty: they are also a safety signal that the arms are fighting.
- **Testability.** Can each block be tested alone? A recorded log could replay camera and force data to test the fusion software without moving any hardware.

None of these questions needs a single part to be bought. That is the value of drawing the diagram first.

### Recap

- A **system block diagram** shows components as blocks and interfaces as labelled lines, one level of detail at a time.
- Lay out data paths to read like **sense–think–act**, and draw power on a separate diagram.
- Label interfaces with **content, units, rate and transport**, and define what happens when data stops.
- Use the diagram to find **single points of failure, timing problems and untestable parts** before building.
- The two-arm platform here is a **proposed design for teaching**, not a built system with results.

> **Interactive:** This explorer fuses a camera that sometimes loses sight of its target with a second, continuous sensor. Raise the dropout probability and watch how the fused estimate copes during camera dropouts. The case study pairs vision with gripper force in a similar spirit — a design idea to explore, not a finding. Try it at https://tactiverge.win/academy/lab/#fusion

#### Project: Paper project: your own block diagram

Choose a robot — your own design idea, or one from earlier lessons, such as the bakery tray-moving arm or the line-follower.

1. List its blocks under the five subsystem headings.
2. Draw a data diagram laid out as sense, think, act, with every line labelled by content, rate and link type. Use made-up but sensible rates, and say so.
3. Draw a separate power diagram, showing where the emergency stop cuts power.
4. Write an interface list with at least four entries, including what happens if data stops arriving.
5. Mark every single point of failure and write one sentence on each.

Use paper, or free diagramming software if you have it. No hardware is needed.

**Deliverables**

- A data block diagram laid out as sense–think–act
- A separate power diagram showing the e-stop
- An interface list with at least four entries and timeout behaviour
- Marked single points of failure with comments

#### Check your understanding

1. Why does the case-study design send force readings on their own link instead of through the vision software?
   A) Force sensors cannot use USB
   B) So force data keeps arriving even when the camera's view is blocked or vision is slow
   C) Because vision software cannot read numbers
   D) To reduce the number of microcontrollers

2. In the case-study power diagram, what does the emergency stop disconnect?
   A) All power, including the computers
   B) Only the camera
   C) Nothing; it sends a software message
   D) The arm motor power, leaving the logic powered so computers keep running and logging

3. What is the status of the TV-01 research question used in this lesson?
   A) A proposed study with no results, used here only as a source of design requirements
   B) A completed study showing force sensing works
   C) A completed study showing force sensing does not work
   D) An industry standard

4. Why must the four processors in the design have synchronised clocks?
   A) So the motors run at the same speed
   B) Because CAN bus requires it to power on
   C) So timestamps from different processors can be compared and logs lined up
   D) To make the camera faster

5. Which is a good convention for a top-level block diagram?
   A) Include every wire and resistor on one page
   B) Show one level of detail, label every line with what crosses it, and draw power separately
   C) Leave lines unlabelled to keep it clean
   D) Draw only the software


---

# Module 3: Sensors and actuators

The devices that let a robot measure the world and move within it, and the imperfections every engineer has to design around.

**Objectives**

- Classify common sensors by what they measure and how they report it.
- Explain noise, resolution, range and drift in sensor readings.
- Compare DC motors, servos and stepper motors for different tasks.
- Describe why gearing trades speed for torque.


## 3.1 How sensors measure

*What happens inside a sensor, and the vocabulary engineers use to judge one: range, resolution, accuracy, precision, noise and bandwidth.* (about 30 min)

### A robot only knows what its sensors tell it

A robot arm that picks up a cup never "sees" the cup the way you do. It receives numbers: a voltage from a joint sensor, a count from a wheel, an array of brightness values from a camera. Everything the robot believes about the world and about itself is built from those numbers. If they are wrong, late or noisy, the robot's decisions will be wrong, late or jittery, no matter how clever its software is.

So before choosing a sensor, an engineer asks a set of standard questions. How does it work? What can it measure, and how finely? How close to the truth is it, and how consistent? How quickly does it respond? This lesson gives you that vocabulary. The rest of the module applies it to real sensor types.

### Transduction: turning the world into a signal

A sensor is a **transducer**: a device that converts one kind of physical quantity into another, usually an electrical signal a computer can read. Some examples:

- A **thermistor** is a resistor whose resistance changes with temperature.
- A **photodiode** produces a small current when light falls on it.
- A **potentiometer** turns a rotation into a voltage, by sliding a contact along a resistive track.
- A **strain gauge** is a thin metal pattern whose resistance changes very slightly when it is stretched.

In each case there is a chain: physical quantity → physical effect → electrical signal → number. Often the raw signal is tiny, so it is amplified, and then an **analog-to-digital converter** (ADC) turns the voltage into a whole number of "counts". Every link in that chain can add error, which is why a sensor's datasheet lists so many characteristics.

### Range and resolution

**Range** is the span of values the sensor can measure. A distance sensor might work from 2 cm to 200 cm. Outside its range, it may report nonsense, report its maximum, or report nothing at all. A robot must know which, because "nothing detected" and "something very close" can look alarmingly similar.

**Resolution** is the smallest change the sensor can report. A kitchen scale that displays whole grams has a resolution of 1 g. A sensor read by a 10-bit ADC has 2¹⁰ = 1024 possible counts; if those counts span 0–200 cm, each count is about 200 / 1024 ≈ 0.2 cm.

Resolution is *not* the same as accuracy. That kitchen scale shows whole grams, but it might be 5 g off. A display with many digits can give a false sense of confidence.

### Accuracy and precision

These two words are often used interchangeably in everyday speech. In engineering they mean different things.

- **Accuracy** is how close the measurements are to the true value, on average. A consistent offset from the truth is called **bias** or **systematic error**.
- **Precision** is how close repeated measurements are to *each other*. Poor precision shows up as scatter.

Picture throwing darts. Tightly grouped darts far from the bullseye are precise but inaccurate. Darts scattered evenly around the bullseye are accurate on average but imprecise. You want both.

The difference matters because the fixes differ. Bias can often be removed by **calibration**: measure something whose true value you know, and subtract the offset. Scatter cannot be calibrated away; it can only be reduced by averaging or filtering, which costs time.

### Worked example

A distance sensor points at a wall that a tape measure says is exactly 50.0 cm away. Here are eight readings (made-up data for illustration), analysed in Python using only the standard library:

```python
import statistics

true_distance = 50.0   # cm, measured carefully with a tape measure
readings = [51.2, 50.8, 51.5, 51.1, 50.9, 51.3, 51.0, 51.4]  # made-up data

mean = statistics.mean(readings)
spread = statistics.stdev(readings)
print(f"mean reading:        {mean:.2f} cm")
print(f"bias (accuracy):     {mean - true_distance:+.2f} cm")
print(f"std dev (precision): {spread:.2f} cm")
```

```
mean reading:        51.15 cm
bias (accuracy):     +1.15 cm
std dev (precision): 0.24 cm
```

This sensor is fairly precise (readings vary by about a quarter of a centimetre) but reads about 1.15 cm too long. Subtracting 1.15 cm from every reading would fix most of the bias. Notice that we needed an independent, trusted measurement (the tape) to discover the bias at all. Without a reference, a biased sensor looks perfectly healthy.

> **Accuracy versus repeatability in robot specs.** Robot arm specification sheets often quote **repeatability** rather than accuracy. Repeatability is precision: how closely the arm returns to the same taught position. Accuracy, how close it gets to a position given as coordinates, is usually worse. You will meet this distinction again when reading robot specifications.

### Noise

**Noise** is the random, unpredictable part of a measurement: the scatter in the example above. It comes from many sources: electrical interference from nearby motors, the random motion of electrons in resistors, vibration, flickering lights, and the rounding performed by the ADC itself.

A useful way to describe a sensor's noise is the **signal-to-noise ratio**: how large the quantity you care about is compared with the random variation. A 0.24 cm wobble is unimportant when measuring a 50 cm distance, but it would swamp a 0.1 cm change you were trying to detect.

The most common response to noise is averaging: if the noise is random, the average of many readings wanders less than any single reading. The price is **lag**. An average of the last ten readings describes where things were a moment ago, not where they are now. That trade-off between smoothness and delay appears throughout robotics.

### Bandwidth and response time

A sensor does not respond instantly. A thermometer dipped in hot water takes several seconds to climb to the new temperature. Engineers describe this using **response time**, or more generally **bandwidth**: roughly, how fast a change the sensor can follow. A sensor with low bandwidth smooths out fast changes, whether you wanted it to or not.

Closely related is the **sample rate**: how many readings per second you take. Suppose a mobile robot drives at 1 m/s and its distance sensor updates 10 times per second. Between readings the robot travels 10 cm, blind. If it needs to stop within 5 cm of an obstacle, that sensor is too slow, however accurate each reading is.

### Putting it together

Imagine choosing a sensor to detect when a gripper has closed on an object. You would ask:

1. **Transduction:** what physical effect does it use, and can that effect occur in my situation? (An optical sensor cannot see through an opaque object.)
2. **Range:** will the forces or distances I care about fall inside it?
3. **Resolution:** can it detect the smallest change that matters?
4. **Accuracy and precision:** is the bias calibratable, and is the scatter small enough?
5. **Noise:** what else in the robot will disturb the signal?
6. **Bandwidth:** can it respond before the gripper crushes the object?

No sensor is best at everything. Engineering is about choosing one whose weaknesses do not matter for the task, and designing around the ones that do.

### Recap

A sensor transduces a physical quantity into a signal. Range is what it can measure; resolution is the finest step it reports; accuracy is closeness to the truth; precision is consistency; noise is the random part; bandwidth is how fast it can follow change. Calibration fixes bias, averaging reduces noise at the cost of delay, and an honest reference measurement is the only way to know which problem you have.

#### Project: Kitchen-table project: characterise a measuring device

Choose a measuring device you already have: a kitchen scale, a ruler, a bathroom scale, or a phone's built-in compass.

1. Find a reference you trust, such as an unopened 500 g packet of food (the printed mass is a reasonable reference) or a known angle.
2. Take at least ten measurements of the same thing, resetting the device each time.
3. Compute the mean, the bias (mean minus reference) and the standard deviation, by hand, in a spreadsheet, or by adapting the Python example.
4. State the device's resolution from its display, and compare it with the scatter you measured.

Write two sentences on whether the device is more limited by accuracy, precision or resolution.

**Deliverables**

- A list of at least ten readings and the reference value
- Calculated mean, bias and standard deviation
- A short verdict on the device's main limitation

#### Check your understanding

1. A sensor's readings are tightly grouped but consistently 3 mm higher than the true value. How would you describe it?
   A) Accurate but imprecise
   B) Precise but inaccurate
   C) Both accurate and precise
   D) Low resolution

2. A 10-bit ADC spans a sensor range of 0–100 °C. What is the approximate resolution?
   A) About 0.1 °C
   B) About 1 °C
   C) About 10 °C
   D) Exactly 0.01 °C

3. Averaging the last 20 readings makes a signal smoother. What is the main cost?
   A) The sensor's range shrinks
   B) The bias is doubled
   C) The resolution gets worse
   D) The smoothed value lags behind real changes

4. A robot drives at 0.5 m/s and its obstacle sensor updates 5 times per second. How far does it travel between readings?
   A) 2.5 cm
   B) 10 cm
   C) 25 cm
   D) 1 m

5. Why do you need an independent reference measurement to discover a sensor's bias?
   A) Because a consistently biased sensor looks perfectly steady on its own; only comparison with a known value reveals the offset
   B) Because bias only appears when the sensor is new
   C) Because averaging always removes bias
   D) Because bias is caused by the reference

**Go further:**

- Wikipedia — Accuracy and precision: https://en.wikipedia.org/wiki/Accuracy_and_precision — Standard definitions, with the dartboard picture and the related terms trueness and repeatability.


## 3.2 Sensing position and motion

*How robots measure their own joints and movement with potentiometers, encoders, accelerometers and gyroscopes, and why integrated measurements drift.* (about 35 min)

### Knowing where you are

Before a robot can control a joint, it has to know the joint's angle. Before a mobile robot can follow a path, it needs some idea of how far it has driven and which way it is facing. Sensors that measure a robot's own state, rather than the outside world, are called **proprioceptive** sensors, after the human sense that tells you where your limbs are with your eyes closed.

This lesson covers the four you will meet most: potentiometers, encoders, accelerometers and gyroscopes.

### Potentiometers: angle as a voltage

A rotary **potentiometer** (often shortened to "pot") is a resistive track with a sliding contact, the **wiper**, attached to a shaft. Put a fixed voltage across the ends of the track and the wiper's voltage is proportional to how far round the shaft has turned.

Suppose a pot has 270° of travel and is supplied with 3.3 V. If the wiper reads 1.10 V:

```
angle = (1.10 / 3.3) × 270° = 90°
```

Pots are cheap, simple and **absolute**: the moment the robot powers on, the voltage says where the joint is. Their weaknesses are a limited angle (most cannot spin continuously), wear of the sliding contact, and electrical noise that limits resolution. A typical hobby servo uses a pot inside it to sense its own output angle.

### Encoders: counting steps of rotation

An **encoder** turns rotation into digital pulses. A common design is a disc with a ring of slots and a light shining through it onto a detector: as the disc turns, the light flickers on and off, and electronics count the flickers. Magnetic encoders do the same with a rotating magnet and a sensor that detects its field.

### Incremental encoders

An **incremental** encoder reports *changes* in angle. Two detectors placed slightly out of step, called **quadrature** channels A and B, let the electronics tell which way the shaft is turning: if A changes before B, it is going one way; if B leads, the other. Counting every rising and falling edge of both channels gives four counts per slot.

Worked example: an encoder with 500 slots per revolution gives 4 × 500 = 2000 counts per revolution, so each count is:

```
360° / 2000 = 0.18°
```

Put that encoder on a wheel 6.5 cm in diameter. One revolution moves the robot one circumference, π × 6.5 ≈ 20.42 cm, so each count is about 0.1 mm of travel. After 15,000 counts:

```
15000 / 2000 = 7.5 revolutions
7.5 × 20.42 cm ≈ 153.2 cm
```

The catch is the word *incremental*. The encoder knows only how far it has moved since it started counting. After power-up, the robot must **home** each joint, for example by moving slowly until it touches a limit switch, to establish where zero is.

### Absolute encoders

An **absolute** encoder reports the actual angle directly, using a disc with a unique pattern at every position. It knows where it is at power-up, which is why many industrial arms use them, at higher cost.

### What encoders cannot tell you

A wheel encoder measures how far the *wheel* turned, not how far the *robot* moved. If the wheel slips on a dusty floor or the robot is pushed, the count and reality disagree. Estimating position by adding up wheel motion is called **odometry**, and its errors grow with distance travelled.

### Inertial sensors: accelerometers and gyroscopes

An **inertial measurement unit** (IMU) packages motion sensors into a small chip, usually tiny micro-machined structures etched in silicon. The two core sensors are the accelerometer and the gyroscope.

### Accelerometers

An **accelerometer** measures acceleration along each of its axes. The surprising detail is that it also measures **gravity**. An accelerometer sitting still on a table reports about 9.81 m/s² pointing up, because the table is pushing it up against gravity. In free fall it reads nearly zero.

That makes an accelerometer a good **tilt sensor** when it is not otherwise accelerating. If a robot is tilted by 30°, gravity splits between two axes:

```
along x: 9.81 × sin 30° ≈ 4.905 m/s²
along z: 9.81 × cos 30° ≈ 8.496 m/s²
tilt = atan2(4.905, 8.496) ≈ 30.0°
```

But once the robot moves, the accelerometer cannot tell the difference between tilting and accelerating. Vibration from motors also makes accelerometer readings noisy.

### Gyroscopes

A **gyroscope** (gyro) measures **angular velocity**: how fast the sensor is rotating, in degrees or radians per second. To get an angle, you add up rate × time at every step, a process called **integration**:

```
angle_new = angle_old + rate × Δt
```

Gyros are smooth and respond quickly, and they do not care about linear acceleration. Their weakness is **bias**: a small, slowly changing offset in the rate reading. Even when the sensor is perfectly still, it might report 0.5 °/s. Integration adds that error up every step.

### Drift: why integrated sensors wander

Here is that effect in Python, with a made-up bias of 0.5 °/s and the robot sitting perfectly still:

```python
bias = 0.5      # deg/s, made-up gyro bias for illustration
dt = 0.01       # 100 readings per second
angle = 0.0
for step in range(1, 6001):   # 60 seconds with the robot perfectly still
    true_rate = 0.0
    measured = true_rate + bias
    angle += measured * dt
    if step % 1500 == 0:
        print(f"t = {step * dt:4.0f} s   estimated angle = {angle:5.1f} deg")
```

```
t =   15 s   estimated angle =   7.5 deg
t =   30 s   estimated angle =  15.0 deg
t =   45 s   estimated angle =  22.5 deg
t =   60 s   estimated angle =  30.0 deg
```

The robot has not moved, yet after a minute it believes it has turned 30°. This steady growth of error is called **drift**.

It is worse for position from an accelerometer, because position needs *two* integrations (acceleration → velocity → position). A constant acceleration bias b produces a position error of ½ · b · t². With b = 0.01 m/s², that is 0.5 m after 10 s and 18 m after 60 s. This is why a phone cannot track your walk around a building using its accelerometer alone.

### Combining strengths

Notice how the weaknesses complement each other. The gyro is smooth and fast but drifts over time. The accelerometer is noisy and confused by motion, but on average it always knows which way is down, so it does not drift. Combining them, trusting the gyro over short times and the accelerometer over long times, gives a tilt estimate better than either. This idea, **sensor fusion**, is developed in the embedded systems pathway. Similarly, wheel odometry is often corrected by an absolute reference such as a camera recognising landmarks.

### Recap

Potentiometers give absolute angle as a voltage but wear and have limited travel. Incremental encoders count fine steps of rotation but need homing; absolute encoders know their angle at power-up. Accelerometers sense acceleration plus gravity, making them tilt sensors when still. Gyros sense rotation rate; integrating them drifts because bias accumulates. Any estimate built by adding up small changes will drift unless something absolute corrects it.

#### Check your understanding

1. An incremental encoder has 1000 slots and is read in quadrature (4 counts per slot). What angle does one count represent?
   A) 0.36°
   B) 0.09°
   C) 0.9°
   D) 4°

2. Why must a robot with incremental encoders usually home its joints after power-up?
   A) To warm up the motors
   B) To calibrate the gyroscope bias
   C) Because incremental encoders only measure changes, so the robot does not know where zero is until it finds a reference
   D) Because absolute encoders require it

3. An accelerometer lying flat and still on a table reads about 9.81 m/s² upward. Why?
   A) It measures the support force resisting gravity, so it senses gravity even when not moving
   B) It is faulty and needs calibrating
   C) The Earth's rotation causes it
   D) It is measuring vibration from the table

4. A still gyro has a bias of 0.2 °/s. After integrating for 2 minutes, roughly how wrong is the angle estimate?
   A) 0.4°
   B) 2.4°
   C) 12°
   D) 24°

5. Why do engineers often combine a gyroscope with an accelerometer to estimate tilt?
   A) Two sensors always cost less than one
   B) The gyro is smooth over short times but drifts; the accelerometer is noisy but does not drift, so together they cover each other's weaknesses
   C) Accelerometers cannot measure tilt at all
   D) Gyroscopes only work when combined with another sensor

**Go further:**

- Wikipedia — Rotary encoder: https://en.wikipedia.org/wiki/Rotary_encoder — Diagrams of absolute and incremental encoders and quadrature signals.
- Wikipedia — Inertial measurement unit: https://en.wikipedia.org/wiki/Inertial_measurement_unit — How IMUs are built and why their errors accumulate over time.


## 3.3 Sensing force, touch and proximity

*How robots feel: strain gauges and load cells for measuring force, force-sensitive resistors for detecting touch, and capacitive and infrared sensors for noticing what is nearby.* (about 30 min)

### Why a robot needs to feel

Cameras tell a robot where things are. They do not tell it how hard it is squeezing, whether an object is slipping, or whether it has just bumped into a person. A gripper picking up an egg and a gripper picking up a brick may look identical to a camera while the egg is breaking. Force and touch sensing close this gap. They matter most at the moment of contact, which is exactly when vision is often blocked by the robot's own hand.

This lesson covers sensors that measure force, sensors that detect touch, and sensors that detect objects *before* contact.

### Strain gauges: measuring tiny stretches

When you push on a solid metal bar, it bends very slightly. Engineers describe the stretching with **strain**: the change in length divided by the original length. Strain has no units and is usually tiny, so it is often written in **microstrain** (µε, millionths). A strain of 500 µε means a 100 mm length has stretched by 0.05 mm.

A **strain gauge** is a thin zig-zag of metal foil glued to a surface. When the surface stretches, the foil gets longer and thinner, and its resistance rises. The sensitivity is described by the **gauge factor**, about 2 for common metal-foil gauges:

```
ΔR / R = gauge factor × strain
```

For a 120 Ω gauge at 500 µε:

```
ΔR = 2 × 0.000500 × 120 Ω = 0.12 Ω
```

That is a change of only 0.1%. Measuring it directly would be hopeless, because temperature changes and the resistance of the wires would drown it. Instead, gauges are wired into a **Wheatstone bridge**: four resistances arranged so that the output voltage is zero when everything is balanced, and only the tiny imbalance caused by strain shows up. An amplifier then boosts that small voltage for the ADC. Bridges can also cancel the effect of temperature, if gauges experience it equally.

### Load cells: strain gauges with a job

A **load cell** is a carefully shaped piece of metal with strain gauges bonded in the places that stretch most under load. It turns force into a predictable strain, and the bridge turns strain into voltage. Kitchen and bathroom scales use load cells.

Load cells are often specified by their **sensitivity** in millivolts of output per volt of excitation (mV/V). A load cell rated for 5 kg at 1 mV/V, powered with 5 V, gives 5 mV at full load: about 1 mV per kilogram, before amplification.

Load cells need **calibration**. A quick two-point calibration, using made-up readings for illustration:

```
no load:           0.12 mV   (offset)
2.000 kg on top:   2.14 mV
gain = 2.000 kg / (2.14 − 0.12) mV ≈ 0.990 kg per mV

unknown object:    1.33 mV
mass ≈ (1.33 − 0.12) × 0.990 ≈ 1.198 kg
force ≈ 1.198 kg × 9.81 m/s² ≈ 11.75 N
```

The embedded systems pathway returns to calibration in detail. The important point here is that a load cell is accurate and linear, but needs careful mounting, an amplifier and calibration. Robots often place a multi-axis force/torque sensor, built from several gauge sections, at the wrist, so they can feel forces and twisting in every direction.

### Force-sensitive resistors: cheap touch

A **force-sensitive resistor** (FSR) is a thin, flexible pad whose resistance drops as you press it. Unpressed, its resistance is very high; pressed firmly, it falls dramatically. Put it in a voltage divider and you have a simple touch sensor for the cost of a small sticker.

FSRs are excellent for answering *"is something touching?"* and *"roughly how hard?"*. They are poor at answering *"exactly how many newtons?"* because:

- the response is strongly **nonlinear** (most of the change happens at light forces);
- different pads of the same type can differ noticeably from each other;
- they show **hysteresis** (pressing and releasing give different readings at the same force) and **creep** (the reading slowly changes under a constant load);
- the reading depends on how the force is spread over the pad.

So engineers choose FSRs for contact detection and grip-or-no-grip decisions, and load cells when the actual force value matters.

### Proximity: sensing before touching

Sometimes a robot wants to know that something is near *before* it makes contact.

**Capacitive sensing** detects changes in the electric field around an electrode. Your finger, being conductive and full of water, changes the capacitance between the electrode and its surroundings. Touchscreens work this way. Capacitive sensors can detect a hand a few centimetres away through a plastic cover, which makes them useful for robot "skins". They respond more strongly to some materials than others, and humidity or nearby metal can shift their readings.

**Infrared (IR) proximity sensors** shine invisible infrared light and measure what bounces back. Simple ones judge distance by how *bright* the reflection is, which means a black object looks farther away than a white one at the same distance. Better designs use **triangulation**: they measure the *angle* at which the reflected spot returns, which depends far less on colour. Both kinds can be confused by strong sunlight, which contains plenty of infrared, and by shiny or transparent surfaces that reflect light away or let it pass through.

### Matching sensor to job

Think about a gripper handling soft, unfamiliar objects such as a sponge or a folded cloth:

- **Is it touching?** An FSR on each fingertip can say yes or no cheaply.
- **How hard is it squeezing?** A small load cell in the finger gives a usable force value.
- **Is something about to collide?** Capacitive or IR sensing on the outside of the hand can warn before contact.

Each one answers a different question. Good designs pick the cheapest sensor that answers the question that matters.

### Recap

Strain gauges turn microscopic stretches into small resistance changes, read through a Wheatstone bridge and amplifier. Load cells package them into accurate force sensors that need calibration. FSRs are cheap, flexible touch detectors with nonlinear, drifting output. Capacitive and IR proximity sensors detect objects before contact, each with its own blind spots: material for capacitive, colour, sunlight and shine for IR.

> **A proposed question, not a result.** Tactiverge's Project TV-01 asks: *"Can inexpensive local force sensing compensate for intermittent visual information and improve cooperative robotic manipulation of unfamiliar deformable materials?"* It is a good example of why touch sensing matters: a camera's view of a cloth is often blocked by the grippers holding it. But TV-01 is a **proposed** study with **no results**. It shows how a question is framed, not that force sensing has been shown to work for this task.

#### Check your understanding

1. A 350 Ω strain gauge with gauge factor 2 experiences a strain of 1000 µε. What is the resistance change?
   A) 0.35 Ω
   B) 0.7 Ω
   C) 7 Ω
   D) 700 Ω

2. Why are strain gauges normally connected in a Wheatstone bridge?
   A) To make the gauge stronger
   B) So that the output is near zero when balanced and the tiny strain-induced imbalance can be amplified, with some temperature effects cancelled
   C) Because the bridge converts force directly into a digital number
   D) To increase the gauge factor to 100

3. A designer needs to know only whether a fingertip is touching an object. Which sensor is the most sensible low-cost choice?
   A) A six-axis wrist force/torque sensor
   B) A stereo camera
   C) A force-sensitive resistor
   D) A gyroscope

4. A brightness-based IR proximity sensor reports a black box as farther away than a white box at the same distance. Why?
   A) Black objects are always farther away
   B) Infrared light travels more slowly near dark objects
   C) Capacitance is lower for black objects
   D) The black surface reflects less infrared light, and the sensor interprets a weaker reflection as greater distance

5. A load cell reads 0.20 mV with no load and 3.20 mV with a 3.000 kg reference mass. What mass gives 1.70 mV?
   A) 1.5 kg
   B) 1.7 kg
   C) 1.0 kg
   D) 2.5 kg

**Go further:**

- Wikipedia — Strain gauge: https://en.wikipedia.org/wiki/Strain_gauge — Gauge factor, bridge circuits and temperature compensation.
- Wikipedia — Force-sensing resistor: https://en.wikipedia.org/wiki/Force-sensing_resistor — How FSRs are built and why their response is nonlinear.


## 3.4 Cameras and depth sensing

*How image sensors capture light, what frame rate and exposure mean for a moving robot, and how stereo, structured light and time of flight measure depth, and fail.* (about 35 min)

### The richest sensor, and the hardest to use

A single camera image contains hundreds of thousands of measurements, enough to recognise objects, read labels and see where a path goes. That richness is why cameras are on almost every modern robot. But an ordinary image is flat: it tells you which direction something is in, not how far away. And cameras are surprisingly easy to fool with glare, darkness, motion or a plain white wall. This lesson covers how cameras capture images, how robots recover depth, and the specific ways each method fails.

### Inside an image sensor

A camera's image sensor is a grid of tiny light-sensitive cells, one per **pixel**. During an **exposure**, each cell collects light and builds up an electrical charge proportional to how much light hit it. The charges are read out and converted to numbers, typically 0–255 for each pixel in an 8-bit image.

The cells themselves cannot tell colours apart. Most colour cameras place a mosaic of red, green and blue filters over the grid, commonly the **Bayer pattern**, and software estimates the full colour at each pixel from its neighbours.

The numbers add up quickly. A modest 640 × 480 image has 307,200 pixels. With three colour values per pixel at 30 frames per second, that is:

```
640 × 480 × 3 × 30 = 27,648,000 bytes per second ≈ 27.6 MB/s
```

That is a lot of data for a small robot computer to move and process, which is one reason robots often use lower resolutions than phones do.

### Frame rate, exposure and motion

**Frame rate** is how many images per second the camera delivers. At 30 frames per second (fps), a new image arrives every 1/30 s ≈ 33 ms. Anything that happens between frames is invisible to the robot.

**Exposure time** is how long each cell collects light. Longer exposures gather more light and less noise, but anything that moves during the exposure is smeared, called **motion blur**. If an object moves at 0.5 m/s and the exposure lasts 10 ms:

```
blur = 0.5 m/s × 0.010 s = 0.005 m = 5 mm
```

In dim light the camera automatically lengthens its exposure, so blur gets worse exactly when the image is already poor.

Many inexpensive sensors use a **rolling shutter**: they read out the image row by row, so the top of the frame is captured slightly earlier than the bottom. A fast-moving object or a vibrating robot can appear tilted or wobbly. A **global shutter** captures every pixel at the same instant and is preferred for fast-moving robots, at higher cost.

### Recovering depth

A single image loses distance information: a small cup nearby and a large cup far away can look identical. Robots recover depth in three main ways.

### Stereo vision

Two cameras side by side, a known distance apart, see the same scene from slightly different positions, just like your two eyes. A nearby object appears in noticeably different places in the two images; a distant one barely shifts. That shift, measured in pixels, is the **disparity** d. For two parallel cameras with focal length f (in pixels) and separation, or **baseline**, B:

```
depth Z = f × B / d
```

With f = 700 pixels and B = 6 cm:

```python
f = 700      # focal length in pixels
B = 6.0      # baseline in cm

for d in [84, 83, 21, 20, 7, 6]:
    Z = f * B / d
    print(f"disparity {d:2d} px  ->  depth {Z:6.1f} cm")
```

```
disparity 84 px  ->  depth   50.0 cm
disparity 83 px  ->  depth   50.6 cm
disparity 21 px  ->  depth  200.0 cm
disparity 20 px  ->  depth  210.0 cm
disparity  7 px  ->  depth  600.0 cm
disparity  6 px  ->  depth  700.0 cm
```

Look at what a one-pixel mistake costs. At 50 cm it shifts the depth by about 6 mm. At 2 m, by 10 cm. At 6 m, by a whole metre. Stereo depth error grows roughly with the *square* of distance, so stereo is precise up close and vague far away. A wider baseline helps, at the cost of a bulkier sensor.

Stereo also needs to **match** points between the two images. On a blank wall, a uniform floor or a repeating pattern like a fence, there is nothing distinctive to match, and stereo gives no answer or a wrong one.

### Structured light

A **structured-light** sensor solves the matching problem by projecting its own pattern, often a field of infrared dots or stripes, and watching it with a camera offset to one side. Surfaces at different depths shift the pattern by different amounts, and the same triangulation geometry as stereo turns those shifts into depth. Because the sensor supplies its own texture, blank walls are no longer a problem.

Its weakness is that its pattern must be visible. Bright sunlight washes out a projected infrared pattern, so many structured-light sensors work well indoors and poorly outside. Very dark surfaces absorb the pattern, and mirrors or glass send it somewhere else.

### Time of flight

A **time-of-flight** (ToF) sensor sends out light and measures how long it takes to return. Light travels about 30 cm per nanosecond, so the timing must be extraordinarily fine. For a target 1 m away, the round trip is 2 m:

```
time = 2 m / (3 × 10⁸ m/s) ≈ 6.67 ns
```

and resolving 1 cm of depth means resolving about 67 picoseconds of round-trip time. Many ToF cameras measure this indirectly, by modulating their light and measuring the shift in phase of the returning wave. Lidar, which sweeps laser beams around a scene, uses the same principle.

ToF sensors work on blank surfaces and give a depth for every pixel at once. Their typical failure is **multipath**: light that bounces off a second surface before returning takes longer, so corners and shiny floors can produce depths that are too long. Dark materials return little light, and transparent objects may be invisible altogether.

### A catalogue of failure modes

It is worth collecting these together, because a robot must be designed around them:

- **Lighting:** too dark (noise, blur), too bright (washed-out pattern), or backlit.
- **Texture:** blank or repeating surfaces defeat stereo matching.
- **Material:** glass and clear plastic are often invisible to depth sensors; mirrors and polished metal give false readings; black fabric absorbs light.
- **Motion:** blur and rolling-shutter distortion.
- **Occlusion:** a camera cannot see what is behind something, including the robot's own gripper.
- **Range:** stereo degrades with distance; projected-light sensors have a limited maximum range.

None of this makes cameras bad sensors. It makes them sensors with known weaknesses, which is exactly why robots combine them with touch, force and motion sensing.

### Recap

An image sensor counts light at each pixel during an exposure; frame rate sets how often the robot gets news, and exposure sets how blurred it is. Stereo infers depth from disparity, Z = f × B / d, precisely nearby and poorly far away. Structured light projects its own texture but struggles in sunlight. Time of flight times light's round trip but suffers from multipath. Each method has failure modes a robot designer must expect.

> **Eye safety with projected light.** Depth sensors and lidars emit infrared or laser light that you cannot see. Commercial sensors are designed and labelled to be eye-safe in normal use, but never stare into an emitter, look at one through magnifying optics, or use a damaged or modified sensor. Leave any laser hardware experiments to supervised settings.

#### Check your understanding

1. A camera exposes each frame for 20 ms while an object crosses the view at 0.25 m/s. How long is the motion blur?
   A) 0.5 mm
   B) 5 mm
   C) 50 mm
   D) 12.5 mm

2. A stereo camera has f = 500 pixels and baseline B = 10 cm. An object shows a disparity of 25 pixels. How far away is it?
   A) 20 cm
   B) 125 cm
   C) 200 cm
   D) 500 cm

3. Why does stereo depth estimation struggle with a plain white wall?
   A) There are no distinctive features to match between the two images
   B) White surfaces reflect too much infrared
   C) The wall is always too far away
   D) Stereo cameras only work outdoors

4. What is multipath error in a time-of-flight sensor?
   A) Two sensors interfering with each other's pattern
   B) Motion blur caused by a long exposure
   C) Light bouncing off an extra surface before returning, so the measured distance is too long
   D) The rolling shutter reading rows at different times

5. A robot must detect clear glass bottles on a shelf. Which concern is most important?
   A) Glass is perfectly visible to all depth sensors
   B) Transparent objects are often invisible or wrongly measured by depth sensors, so another sensing method may be needed
   C) Glass makes stereo baselines longer
   D) Only frame rate matters for glass

**Go further:**

- Wikipedia — Computer stereo vision: https://en.wikipedia.org/wiki/Computer_stereo_vision — Disparity, matching and the geometry behind depth from two cameras.
- Wikipedia — Time-of-flight camera: https://en.wikipedia.org/wiki/Time-of-flight_camera — Direct and phase-based time-of-flight methods and their typical errors.
- Wikipedia — Structured-light 3D scanner: https://en.wikipedia.org/wiki/Structured-light_3D_scanner — How projected patterns are used to recover 3D shape.


## 3.5 Actuators

*How the three most common electric actuators in small robots work, how each is controlled, and when to choose a brushed DC motor, a servo or a stepper.* (about 35 min)

### Turning decisions into motion

Sensing and thinking achieve nothing until something moves. In small and medium robots, that something is nearly always an electric motor. But "motor" covers devices that behave very differently. A brushed DC motor spins freely when powered; a hobby servo holds a commanded angle; a stepper moves in precise, countable steps. Choosing the wrong one makes a robot clumsy, inaccurate or needlessly complicated. This lesson explains how each works, how you command it, and where it fits.

### Brushed DC motors

Inside a **brushed DC motor**, a coil of wire sits between permanent magnets. Current through the coil makes it an electromagnet, which is pushed round by the permanent magnets. Just as it would settle, a rotating switch called the **commutator**, touched by sliding contacts called **brushes**, reverses the current so the push continues. The result is continuous rotation.

Two simple relationships describe it well:

- **Speed rises with voltage.** More voltage, faster spinning (for a given load).
- **Torque rises with current.** The harder the motor has to push, the more current it draws.

When a motor is held still while powered, it is **stalled**: it produces its maximum torque and draws its maximum current, often many times its normal running current. Stalls are when motors and the electronics driving them overheat.

### Controlling a DC motor

To vary speed, controllers rarely vary the voltage smoothly. Instead they use **pulse-width modulation** (PWM): switching the full voltage on and off thousands of times per second. The fraction of time it is on is the **duty cycle**. At 60% duty from a 12 V supply, the motor behaves roughly as if it had an average of 0.6 × 12 = 7.2 V. The motor's inertia smooths out the pulses.

To reverse direction, you reverse the current, using an **H-bridge**: four electronic switches arranged so that either pair can connect the motor's terminals one way round or the other. Motor driver chips package an H-bridge with protection circuits.

### Strengths and weaknesses

Brushed DC motors are cheap, simple, efficient enough and can spin fast. Their weaknesses: the brushes wear and create electrical noise, and the motor has **no idea of its own position**. To control angle you must add a sensor, usually an encoder, and a feedback controller. Most DC motors also spin too fast with too little torque for a robot joint, so they are paired with a gearbox, the subject of the next lesson.

Brushless DC motors move the commutation into electronics, removing the brushes. They last longer and are used in drones and many modern robot joints, but need more complex drive electronics.

### Servos

A hobby **servo** is a package: a small DC motor, a gearbox, a potentiometer on the output shaft and a little control circuit. You tell it an angle, and its internal feedback loop drives the motor until the potentiometer says the output has arrived, then holds it there against disturbances.

The command is a pulse repeated about every 20 ms (50 times per second). The pulse width sets the angle: commonly about 1.0 ms for one end of travel, 1.5 ms for the middle and 2.0 ms for the other end. Exact values and range vary between models. For a servo with 180° of travel mapped linearly over 1.0–2.0 ms:

```
angle = (pulse − 1.0 ms) / 1.0 ms × 180°
pulse 1.25 ms → (0.25 / 1.0) × 180° = 45°
```

Servos are wonderfully convenient: position control in one part, with three wires. The trade-offs: limited travel, modest torque and precision in cheap models, gears that can strip if forced, and usually no way to read back the actual position or force. Larger industrial "servo motors" use the same idea, a motor with built-in feedback, at much higher performance.

### Stepper motors

A **stepper motor** has several sets of coils around a toothed rotor. Energising the coils in sequence pulls the rotor round one small, fixed **step** at a time. A very common design has 200 full steps per revolution:

```
360° / 200 = 1.8° per step
```

Stepper drivers can also **microstep**, sharing current between coils to place the rotor between full steps. With 1/16 microstepping, one revolution takes 200 × 16 = 3200 microsteps, though the real accuracy of each microstep is less certain than of a full step.

The great attraction is **open-loop positioning**: if you send a known number of steps, the shaft turns a known amount, with no position sensor needed. A stepper turning an 8 mm-per-revolution lead screw needs 3200 / 8 = 400 microsteps per millimetre, so a 25 mm move is 10,000 microsteps. This is how many 3D printers and plotters position their heads.

The weaknesses are just as important:

- **Missed steps.** If the load is too great or you accelerate too quickly, the rotor fails to follow, and the controller does not know. Every later position is then wrong by a fixed amount, which is why such machines home themselves at the start.
- **Torque falls with speed.** Steppers are strong at low speed and weak at high speed.
- **Constant current.** A stepper draws current to hold position even when stationary, so it gets warm and wastes energy.
- **Vibration and noise,** especially at certain speeds where the steps excite resonance.

Adding an encoder to a stepper to catch missed steps is increasingly common, which blurs the line with closed-loop motors.

### Choosing between them

A quick guide, based on what the task needs:

- **Continuous rotation, speed matters, position does not** (wheels, fans, pumps): a brushed or brushless DC motor, perhaps with an encoder for speed control.
- **Simple angle positioning, light loads, limited travel** (a pan–tilt camera head, a toy arm, a small gripper): a hobby servo.
- **Repeatable positioning at low to moderate speed without a sensor** (printers, plotters, camera sliders): a stepper, with homing.
- **High performance joints** that must be fast, strong, precise and safe around people: a motor with an encoder and a carefully tuned feedback controller, usually through a gearbox.

Notice that the most capable option is also the one that relies most on the control ideas in the feedback module. Actuators and control are two halves of one problem.

### Recap

Brushed DC motors spin with speed set by voltage (via PWM) and torque by current, reverse through an H-bridge, and need a sensor to know their position. Servos bundle motor, gears, potentiometer and controller to hold a commanded angle set by pulse width. Steppers move in fixed steps for open-loop positioning but can silently miss steps and lose torque at speed. Choose by what the task needs: speed, convenience or countable position.

> **Moving parts and stalled motors.** Even small motors can pinch fingers, catch hair and loose clothing, and get hot when stalled. Motor drivers and batteries can overheat if wired wrongly. If you build anything with motors, work with an adult, use low-voltage supplies and battery packs designed for hobby electronics, keep fingers clear of gears and moving links, and disconnect power before touching the mechanism.

#### Project: Paper project: pick the actuator

For each of these five robot parts, choose a brushed DC motor, a hobby servo or a stepper motor, and justify your choice in two or three sentences using the strengths and weaknesses from this lesson:

1. The drive wheels of a small floor-cleaning robot.
2. The jaw of a small gripper that only needs to be open or closed.
3. The pen-lifting and pen-moving axes of a drawing plotter.
4. A camera on a tilting mount that must point at a chosen angle.
5. A turntable that must rotate an object exactly 37.8° between photographs.

For the turntable, calculate how many full steps of a 200-step-per-revolution stepper are needed, and whether 1/16 microstepping is required.

This is a paper exercise. No hardware is needed.

**Deliverables**

- An actuator choice and justification for each of the five parts
- The step calculation for the turntable
- One sentence on what could go wrong with each choice

**Safety (adult supervision required):** This activity is on paper only. If you later test any idea with real motors, do so only with adult supervision, use low-voltage supplies or hobby battery packs, keep fingers and hair away from moving parts, and disconnect power before adjusting anything.

#### Check your understanding

1. A DC motor is driven by PWM at 25% duty cycle from a 12 V supply. Roughly what average voltage does it see?
   A) 3 V
   B) 9 V
   C) 12 V
   D) 0.25 V

2. What tells a hobby servo which angle to move to?
   A) The supply voltage
   B) The number of pulses sent per second
   C) The width of a pulse repeated about every 20 ms
   D) The current drawn by the motor

3. A 200-step stepper is commanded to turn exactly 90°. How many full steps is that?
   A) 45
   B) 18
   C) 90
   D) 50

4. Why can an open-loop stepper system end up permanently wrong in position?
   A) Steppers drift like gyroscopes
   B) If the motor misses steps under heavy load or fast acceleration, the controller does not know and every later position is offset
   C) The step angle changes as the motor warms up
   D) Microstepping always loses half the steps

5. Which is the best match for the drive wheels of a small mobile robot?
   A) A hobby servo with 180° travel
   B) A stepper with no homing
   C) A DC motor with a gearbox, plus an encoder if speed or distance must be controlled
   D) A load cell

**Go further:**

- Wikipedia — Brushed DC electric motor: https://en.wikipedia.org/wiki/Brushed_DC_electric_motor — How commutators and brushes work, and how speed and torque relate.
- Wikipedia — Stepper motor: https://en.wikipedia.org/wiki/Stepper_motor — Stepper types, drive methods, microstepping and resonance.
- Wikipedia — Servomotor: https://en.wikipedia.org/wiki/Servomotor — The general idea of a motor with built-in position feedback.


## 3.6 Torque, speed and gearing

*Read a motor's torque–speed curve, see how a gearbox trades speed for torque, and size a motor and gear ratio for a robot joint with a complete worked example.* (about 40 min)

### Strong enough and fast enough

A robot joint has two jobs at once. It must be **strong enough** to lift and hold its load, and **fast enough** to finish a motion in reasonable time. An actuator that is too weak sags or stalls; one that is too slow makes the robot useless; one that is oversized wastes money, mass and energy, and the extra mass makes every other joint's job harder. This lesson gives you the tools to size an actuator: torque, the torque–speed curve, gear ratios and a margin for uncertainty.

### Torque

**Torque** is the turning effect of a force. Push on a spanner and the torque on the nut is the force times the perpendicular distance from the nut to where you push:

```
τ = F × r
```

Torque is measured in newton-metres (N·m). Pushing with 20 N at 0.25 m gives 5 N·m. Pushing at twice the distance with half the force gives the same torque.

For a robot arm the main force is **gravity**. A mass m weighs m × g newtons (g ≈ 9.81 m/s²), and the torque it creates on a joint depends on how far out horizontally it is. Worst case is when the arm is horizontal, because the full length acts as the lever.

### The torque–speed curve

A brushed DC motor cannot deliver its maximum torque and maximum speed at the same time. The relationship is close to a straight line:

- At **no load**, it spins at its **no-load speed** but delivers almost no torque.
- Held still, it delivers its **stall torque** at zero speed.
- In between, speed falls steadily as load torque rises:

```
speed = no_load_speed × (1 − torque / stall_torque)
```

Mechanical power is torque times angular speed (in radians per second). It is zero at both ends of the line and greatest in the middle, at half the stall torque and half the no-load speed:

```
P_max = stall_torque × no_load_speed / 4
```

There is a further practical limit. Current, and therefore heat, rises with torque. Running continuously near stall will overheat most small motors. Datasheets often give a **rated** or **continuous** torque well below stall torque, and that is the number to respect for loads held for long periods.

### Gearing: trading speed for torque

Small motors typically spin at thousands of revolutions per minute (rpm) with a small fraction of a newton-metre of torque. Robot joints need tens of rpm and newton-metres of torque. A **gearbox** bridges that gap.

A gear ratio N : 1 means the motor turns N times for each turn of the output. Ideally the output turns N times slower and N times stronger, because power in equals power out. Real gears lose some energy to friction, captured by an **efficiency** η (eta) between 0 and 1:

```
output speed  = motor speed / N
output torque = motor torque × N × η
```

A 100 : 1 gearbox with 70% efficiency turns 0.05 N·m of motor torque into 0.05 × 100 × 0.7 = 3.5 N·m, and 5000 rpm into 50 rpm.

Gearboxes bring side effects, too. They add **backlash**, a little free play when the direction reverses, which hurts precision. High ratios multiply friction, and some (such as worm gears) cannot be **back-driven**, so the joint holds its position with the power off but cannot be pushed out of the way by a person. The motor's own inertia also appears much larger at the output, which affects how quickly the joint can accelerate.

### Worked example: sizing a shoulder joint

Here is a full sizing calculation. All motor figures are **made up for illustration**; real values come from a datasheet.

**The task.** A small arm's shoulder joint must lift a 0.5 kg payload held 0.30 m from the joint. The arm link itself has a mass of 0.2 kg with its centre of mass 0.15 m from the joint.

**Step 1: worst-case static torque.** With the arm horizontal:

```
τ = g × (0.5 × 0.30 + 0.2 × 0.15)
  = 9.81 × (0.15 + 0.03)
  = 9.81 × 0.18
  ≈ 1.77 N·m
```

**Step 2: add a margin.** Moving the arm needs extra torque to accelerate it, the payload might be heavier than planned, and gear efficiency varies. We will require a peak output torque of at least **2 × 1.77 ≈ 3.53 N·m**. Choosing that factor of 2 is a judgement call; record it so others can question it.

**Step 3: speed requirement.** The joint should swing 90° in about a second. Allowing for speeding up and slowing down, we ask for at least **20 rpm** at the output while carrying the 1.77 N·m load.

**Step 4: the candidate motor** (hypothetical): stall torque 0.06 N·m, no-load speed 5000 rpm, gearbox efficiency 70%.

**Step 5: try several gear ratios.** For each ratio, compute the peak output torque, how hard the motor works to carry the load, and the resulting output speed from the torque–speed line:

```python
g = 9.81
load_torque = g * (0.5 * 0.30 + 0.2 * 0.15)   # N·m, static worst case
needed_peak = 2 * load_torque                  # design margin of 2
stall, no_load_rpm, eff = 0.06, 5000, 0.7      # made-up motor and gearbox

print(f"load torque {load_torque:.2f} N·m, peak needed {needed_peak:.2f} N·m")
for N in [50, 75, 100, 150, 200]:
    peak = stall * N * eff
    fraction = load_torque / (N * eff) / stall   # share of motor stall torque
    rpm = no_load_rpm * (1 - fraction) / N if fraction < 1 else 0.0
    ok = peak >= needed_peak and rpm >= 20
    print(f"N={N:3d}  peak {peak:4.2f} N·m  motor at {fraction:4.0%} of stall"
          f"  speed {rpm:4.1f} rpm  {'OK' if ok else 'no'}")
```

```
load torque 1.77 N·m, peak needed 3.53 N·m
N= 50  peak 2.10 N·m  motor at  84% of stall  speed 15.9 rpm  no
N= 75  peak 3.15 N·m  motor at  56% of stall  speed 29.3 rpm  no
N=100  peak 4.20 N·m  motor at  42% of stall  speed 29.0 rpm  OK
N=150  peak 6.30 N·m  motor at  28% of stall  speed 24.0 rpm  OK
N=200  peak 8.40 N·m  motor at  21% of stall  speed 19.7 rpm  no
```

**Step 6: interpret.** Too low a ratio (50 or 75) cannot provide the peak torque; at 50 : 1 the motor would be working at 84% of stall just to hold the arm up, and would overheat. Too high a ratio (200) is strong but too slow. Both 100 : 1 and 150 : 1 meet the requirements. Notice that the speed is not simply highest at the lowest ratio: at low ratios the motor is so heavily loaded that it slows down on its own torque–speed line.

Between the two, 150 : 1 runs the motor at only 28% of stall, so it draws less current and runs cooler when holding the arm, while 100 : 1 is faster. If the arm will often hold its load still for long periods, 150 : 1 is the safer choice, provided the motor's continuous torque rating supports 28% of stall. That is the sort of check you would now make on the datasheet.

### Common mistakes

- **Forgetting the link's own mass.** Here it added 9.81 × 0.2 kg × 0.15 m ≈ 0.29 N·m, about 17% of the total.
- **Using stall torque as if it were usable.** Stall is a limit, not an operating point.
- **Ignoring efficiency.** Gearboxes are never 100% efficient, and high ratios are often less efficient.
- **Mixing units.** rpm and rad/s differ by a factor of 2π/60; grams and kilograms by 1000.

### Recap

Torque is force times lever arm; gravity on a horizontal arm sets the worst static case. A DC motor's speed falls linearly as torque rises, with peak power at half stall torque and half no-load speed. A gear ratio N divides speed by N and multiplies torque by N × η. To size a joint: find the worst-case torque, add a stated margin, set a speed requirement, then test gear ratios against the motor's torque–speed line and its continuous rating.

#### Project: Calculator or Python project: size an elbow joint

Using the same hypothetical motor (stall torque 0.06 N·m, no-load speed 5000 rpm, gearbox efficiency 70%), size the **elbow** of the same arm.

The elbow sits 0.15 m from the shoulder, so it carries the payload (0.5 kg) at 0.15 m and a forearm link of 0.1 kg with its centre 0.075 m from the elbow.

1. Compute the worst-case static torque at the elbow.
2. Apply a margin of 2 and require at least 30 rpm under the static load.
3. Test gear ratios of 30, 50, 75 and 100, by hand or by adapting the Python program.
4. Recommend a ratio and explain the trade-off you made.

This is a calculation exercise; no hardware is needed.

**Deliverables**

- The elbow's static torque calculation with units
- A table of peak torque, motor load fraction and output speed for each ratio
- A recommended gear ratio with a short justification

**Safety (adult supervision required):** This is a paper and computer exercise. If you later build a powered joint, work only with adult supervision, use low-voltage supplies, keep fingers clear of gears and moving links, and never hold a motor stalled for long because it can overheat.

#### Check your understanding

1. A 1.2 kg mass hangs 0.25 m from a horizontal joint. Using g = 9.81 m/s², what torque must the joint supply to hold it?
   A) 0.30 N·m
   B) 2.94 N·m
   C) 4.71 N·m
   D) 11.8 N·m

2. A motor with 0.04 N·m stall torque drives a 50 : 1 gearbox with 80% efficiency. What is the peak output torque?
   A) 2.5 N·m
   B) 0.032 N·m
   C) 2.0 N·m
   D) 1.6 N·m

3. On a linear DC motor torque–speed curve, where is mechanical output power greatest?
   A) At stall, where torque is largest
   B) At no load, where speed is largest
   C) At half the stall torque and half the no-load speed
   D) Power is the same everywhere on the curve

4. Why might an engineer pick a higher gear ratio than the minimum that meets the torque requirement?
   A) To make the joint faster
   B) So the motor works at a smaller fraction of its stall torque, drawing less current and running cooler when holding a load
   C) Because higher ratios remove backlash
   D) Because gear efficiency always rises with ratio

5. A joint's static torque is 2 N·m and the engineer applies a margin of 2. Which statement is the best practice?
   A) Choose a motor and gearbox whose stall torque at the output is exactly 2 N·m
   B) Ignore the margin if the motor looks large enough
   C) Require at least 4 N·m of peak output torque and record why a margin of 2 was chosen
   D) Use a margin only for mobile robots

**Go further:**

- Wikipedia — Gear train: https://en.wikipedia.org/wiki/Gear_train — Gear ratios, mechanical advantage and how torque and speed trade off.


---

# Module 4: Mathematical foundations of movement

The geometry robots use to describe where they are and where their parts will go: coordinates, angles, vectors and the kinematics of a simple arm.

**Objectives**

- Convert between degrees and radians and use sine and cosine to find the components of a vector.
- Describe positions in a coordinate frame and add vectors tip to tail.
- Compute the forward kinematics of a two-link planar arm.
- Explain why inverse kinematics can have zero, one or two solutions, and solve a simple case.


## 4.1 Coordinates, angles and vectors

*The language of position and direction: coordinate frames, radians, sine and cosine, and adding vectors tip to tail.* (about 30 min)

### Why robots need geometry

A robot arm reaching for a cup has to answer a deceptively simple question: *where is my hand right now, and where do I want it to be?* A robot cannot point and say "over there". It needs numbers. This lesson builds the small toolkit of geometry that robots use to turn positions and directions into numbers they can compute with. If some of it is familiar from school, good — we will connect it to motion as we go.

### Coordinate frames

A **coordinate frame** is a reference for measuring positions. In two dimensions it is an origin (a point we call zero) and two perpendicular axes, usually called x and y. Any point can then be written as a pair of numbers (x, y): how far along each axis you must travel from the origin to reach it.

The crucial idea in robotics is that **there is more than one frame**. The same cup can be described from the table's corner, from the robot's base, or from the camera mounted above. Its coordinates are different in each frame, even though the cup has not moved. Much of the mathematics of robotics is about converting a position from one frame to another — "the camera sees the cup at this spot; where is that relative to my shoulder?"

For now we will use a single frame fixed at the base of a robot arm, with x pointing right and y pointing up, and we will measure angles **anticlockwise from the positive x-axis**. This convention is standard in mathematics and robotics, and sticking to one convention avoids a great many mistakes.

### Degrees and radians

You probably measure angles in degrees, where a full turn is 360°. Engineers and programmers also use **radians**. The idea behind radians is natural: wrap a piece of string the length of a circle's radius around its edge. The angle it covers is one radian. Because a circle's circumference is 2π times its radius, a full turn is 2π radians.

So:

- 360° = 2π rad
- 180° = π rad
- 90° = π/2 rad
- 1 rad ≈ 57.3°

To convert, multiply by π/180 (degrees to radians) or by 180/π (radians to degrees). This matters in practice because most programming languages, including Python, expect angles in radians in their trigonometry functions. Passing 90 to a sine function when you meant 90° is a classic bug: the computer will happily compute the sine of 90 radians instead.

### Sine and cosine as "how much along each axis"

Imagine a stick of length L pinned at the origin and pointing at an angle θ (theta) above the x-axis. Where is its tip?

The tip is some distance to the right and some distance up. Cosine and sine are precisely the functions that tell you these amounts for a stick of length 1:

- the tip is **cos θ** along x,
- and **sin θ** along y.

For a stick of length L, scale both by L:

```
x = L · cos θ
y = L · sin θ
```

Check the intuition with easy angles. At θ = 0° the stick lies flat along x: cos 0° = 1 and sin 0° = 0, so the tip is at (L, 0). At θ = 90° it points straight up: cos 90° = 0 and sin 90° = 1, so the tip is at (0, L). At 45° the stick is halfway between, and both cos 45° and sin 45° equal about 0.707 — the tip is equally far right and up.

### Worked example

A link 10 cm long is rotated 30° from the x-axis. Using cos 30° ≈ 0.866 and sin 30° = 0.5:

```
x = 10 · 0.866 = 8.66 cm
y = 10 · 0.5   = 5.00 cm
```

The tip is at about (8.66, 5.00). As a sanity check, x² + y² = 75.0 + 25.0 = 100, and √100 = 10, which is the link length. The tip is exactly as far from the origin as it should be — this is Pythagoras' theorem in action.

### Vectors

A **vector** is a quantity with both a size and a direction, such as "10 cm at 30°". The stick above is a vector. We can write it either in **polar form** (length and angle) or in **component form** (its x and y parts, here (8.66, 5.00)). Sine and cosine convert polar to components. Going the other way:

```
length = √(x² + y²)
angle  = atan2(y, x)
```

The function **atan2** is a two-argument version of the inverse tangent. It looks at the signs of both x and y to work out which quarter of the plane the vector points into, so it returns the correct angle all the way around the circle. The ordinary one-argument inverse tangent cannot tell (1, 1) apart from (−1, −1), because y/x is the same for both. Robotics code uses atan2 almost everywhere for this reason.

### Adding vectors tip to tail

Here is the idea that unlocks robot arms. If you walk 3 m east and then 4 m north, where are you relative to where you started? You add the two movements **tip to tail**: start the second where the first ends. In components, you just add the x parts and add the y parts:

```
(3, 0) + (0, 4) = (3, 4)
```

and your distance from the start is √(3² + 4²) = 5 m.

A robot arm is a chain of vectors, one per link. The first link starts at the base. The second link starts where the first ends. The position of the hand is simply the sum of all the link vectors. The only subtlety is working out the direction each link points, because a link's direction depends on all the joints before it. That is exactly the subject of the next lesson.

> **Precision and rounding.** In the worked example we rounded cos 30° to 0.866. Computers carry many more digits, but they still round. When you compare computed positions, check whether they are *close enough* for the task — a millimetre may be fine for a toy arm and far too much for a surgical one — rather than whether they are exactly equal.

#### Check your understanding

1. How many radians are in a half turn (180°)?
   A) 1
   B) π
   C) π/2
   D) 2π

2. A link of length 4 points at 90° (straight up). Where is its tip?
   A) (4, 0)
   B) (2.83, 2.83)
   C) (0, 4)
   D) (0, 0)

3. Why does robotics code prefer atan2(y, x) over a plain inverse tangent of y/x?
   A) atan2 runs faster
   B) atan2 works in degrees only
   C) atan2 uses the signs of x and y to return the correct angle in all four quarters of the plane
   D) A plain inverse tangent cannot be computed by a computer

4. You move along the vector (2, 5) and then along (3, −1). What is your total displacement?
   A) (6, −5)
   B) (−1, 6)
   C) (5, 6)
   D) (5, 4)

**Go further:**

- MIT OpenCourseWare — 18.06 Linear Algebra: https://ocw.mit.edu/courses/18-06-linear-algebra-spring-2010/ — A famous free university course on vectors and matrices — the mathematics behind coordinate transformations. Best for students who want a serious challenge.


## 4.2 Forward and inverse kinematics of a two-link arm

*Work out where a simple robot arm's hand will be from its joint angles, and then reverse the problem to find joint angles that reach a target.* (about 40 min)

### Two directions of the same problem

**Kinematics** is the study of motion without worrying about the forces that cause it. For a robot arm, it is the geometry connecting two descriptions of the same arm:

- **Joint space**: the angles of each joint.
- **Task space**: the position of the hand (end effector) in the world.

Going from joint angles to hand position is called **forward kinematics**. It answers, "If I set the joints like this, where does the hand end up?" Going the other way, from a desired hand position to the joint angles that achieve it, is **inverse kinematics**. It answers, "I want my hand *there* — how should I set my joints?" Robots need both, and as you will see, they are very different in difficulty.

### The setup

We will study the simplest interesting arm: two links moving in a flat plane, like an arm lying on a table.

- Link 1 has length **L₁** and is attached to the base at the origin by a revolute joint with angle **θ₁**, measured anticlockwise from the x-axis.
- Link 2 has length **L₂** and is attached to the end of link 1 by a second revolute joint with angle **θ₂**, measured **relative to link 1**. So θ₂ = 0 means the arm is straight.

That last detail matters. Because θ₂ is measured relative to link 1, the absolute direction of link 2 in the world is **θ₁ + θ₂**. When you raise your shoulder, your forearm rises too, even if your elbow does not move.

### Forward kinematics

Using the last lesson's tools, the elbow (end of link 1) is at:

```
elbow_x = L₁ · cos θ₁
elbow_y = L₁ · sin θ₁
```

Link 2 is a vector of length L₂ pointing at angle θ₁ + θ₂. Add it tip to tail:

```
x = L₁ · cos θ₁ + L₂ · cos(θ₁ + θ₂)
y = L₁ · sin θ₁ + L₂ · sin(θ₁ + θ₂)
```

That is the complete forward kinematics of a two-link planar arm. Every term has a physical meaning: the first term is link 1's contribution; the second is link 2's.

### Worked example

Take L₁ = 10 cm, L₂ = 8 cm, θ₁ = 30° and θ₂ = 45°. Link 2 therefore points at 30° + 45° = 75°.

```
x = 10 · cos 30° + 8 · cos 75°
  = 10 · 0.8660  + 8 · 0.2588
  = 8.660 + 2.071
  ≈ 10.73 cm

y = 10 · sin 30° + 8 · sin 75°
  = 10 · 0.5000  + 8 · 0.9659
  = 5.000 + 7.727
  ≈ 12.73 cm
```

The hand is at about (10.73, 12.73). Its distance from the base is √(10.73² + 12.73²) ≈ 16.65 cm — less than the full reach of 18 cm, which makes sense because the elbow is bent.

Forward kinematics is always straightforward: plug in the angles and compute. There is exactly one answer.

### Exploring the arm

Before tackling the inverse problem, build some intuition with the explorer below. Try these experiments:

1. Set the second joint to 0 and sweep the first. The hand traces a circle of radius L₁ + L₂.
2. Fold the second joint as far as it goes. How close to the base can the hand get?
3. Pick a target point inside the reach. Can you find **two** different arm shapes that put the hand there?

> **Interactive:** Change the joint angles and watch the hand move. Try to reach the same point with the elbow bent up and with it bent down. Try it at https://tactiverge.win/academy/lab/#kinematics

### Inverse kinematics

Now the hard direction. Given a target (x, y), find θ₁ and θ₂.

The trick is to work out the elbow angle first, using only distances. Let r be the distance from the base to the target, so r² = x² + y². The base, the elbow and the hand form a triangle with sides L₁, L₂ and r. The **law of cosines** relates the sides of any triangle to its angles, and for this arm it gives:

```
r² = L₁² + L₂² + 2 · L₁ · L₂ · cos θ₂
```

You can check it against the worked example: 100 + 64 + 2 · 10 · 8 · cos 45° = 164 + 113.1 = 277.1, and 16.65² ≈ 277.2. It matches, up to rounding. Rearranging:

```
cos θ₂ = (r² − L₁² − L₂²) / (2 · L₁ · L₂)
```

Cosine values must lie between −1 and 1. This simple fact tells you the workspace:

- If the right-hand side is **greater than 1**, the target is too far away: r > L₁ + L₂. **No solution.**
- If it is **less than −1**, the target is too close: r < |L₁ − L₂|. **No solution.**
- If it is **exactly 1 or −1**, the arm must be fully straight or fully folded. **One solution.**
- Otherwise, there are **two** angles with that cosine, +θ₂ and −θ₂. These are the "elbow down" and "elbow up" shapes you may have found in the explorer. **Two solutions.**

Once θ₂ is known, the shoulder angle follows:

```
θ₁ = atan2(y, x) − atan2(L₂ · sin θ₂, L₁ + L₂ · cos θ₂)
```

In words: point at the target, then subtract the angle by which the bent elbow swings the hand off that line.

### Worked example

Same arm (L₁ = 10, L₂ = 8). Target: (12, 6).

```
r² = 12² + 6² = 180
cos θ₂ = (180 − 100 − 64) / (2 · 10 · 8) = 16 / 160 = 0.1
θ₂ ≈ ±84.26°
```

Take θ₂ = +84.26°. Then L₂ · sin θ₂ ≈ 7.960 and L₁ + L₂ · cos θ₂ = 10 + 0.8 = 10.8.

```
θ₁ = atan2(6, 12) − atan2(7.960, 10.8)
   ≈ 26.57° − 36.39°
   ≈ −9.82°
```

Check with forward kinematics: 10 · cos(−9.82°) + 8 · cos(74.44°) ≈ 9.85 + 2.15 = 12.00, and 10 · sin(−9.82°) + 8 · sin(74.44°) ≈ −1.71 + 7.71 = 6.00. It works. The other solution, θ₂ = −84.26°, gives θ₁ ≈ 26.57° + 36.39° = 62.96°, and also lands on (12, 6).

**Always verify an inverse solution with forward kinematics.** It is the easiest way to catch a sign error.

### Why this matters

Real arms have more joints and move in three dimensions, but the pattern holds. Forward kinematics is a direct calculation. Inverse kinematics can have no solution, one, two or infinitely many (for redundant arms), and the robot must choose among them — perhaps the one that avoids an obstacle, stays within joint limits, or requires the least motion from where the arm is now.

#### Project: Paper and calculator project: map a workspace

Choose your own link lengths for a two-link arm (for example L₁ = 6 and L₂ = 4).

1. On squared paper, draw the inner and outer edges of the workspace.
2. Pick five target points: two well inside, one on the outer edge, one inside the inner hole and one outside the reach.
3. For each, compute cos θ₂ and decide how many solutions exist.
4. For one target with two solutions, compute both pairs of angles and check them with forward kinematics. Sketch both arm shapes.

A calculator in degree mode is enough. If you know some Python, you may write a short program instead — remember that Python's `math` functions use radians.

**Deliverables**

- A scale drawing of the workspace with your five targets marked
- A table of r², cos θ₂ and the number of solutions for each target
- Both joint-angle solutions for one target, verified by forward kinematics

#### Check your understanding

1. In a two-link arm with θ₂ measured relative to link 1, which angle gives the absolute direction of link 2?
   A) θ₁ + θ₂
   B) θ₂
   C) θ₁ − θ₂
   D) θ₁ · θ₂

2. With L₁ = 10 and L₂ = 8, both joints at 0°, where is the hand?
   A) (0, 18)
   B) (18, 0)
   C) (10, 8)
   D) (2, 0)

3. For a target, the inverse kinematics formula gives cos θ₂ = 1.4. What does this mean?
   A) There are two solutions
   B) The target is out of reach — there is no solution
   C) The arm must be fully folded
   D) θ₂ = 1.4 radians

4. Why is it good practice to run forward kinematics on an inverse kinematics answer?
   A) It makes the robot move faster
   B) Forward kinematics chooses between elbow-up and elbow-down
   C) It confirms that the computed joint angles really place the hand at the target, catching sign and rounding mistakes
   D) It is required by law

5. Which statement about inverse kinematics for a two-link planar arm is true?
   A) There is always exactly one solution
   B) It never has a solution
   C) It only works when θ₁ = 0
   D) A reachable target usually has two solutions: elbow up and elbow down


## 4.3 Rotations in 2D

*Describe turning with a rotation matrix, compose rotations by multiplying matrices, and learn the crucial difference between rotating a point and rotating a frame.* (about 35 min)

### Why rotation needs its own tool

Robots turn constantly. A mobile robot changes its heading; a shoulder joint swings a whole arm; a camera on a pan head looks left and right. Every time something rotates, the coordinates of everything attached to it change. In the two-link arm lesson you handled this with sine and cosine for one link at a time, and by adding angles (θ₁ + θ₂) for the second link. That works for two links in a plane, but it gets unmanageable fast. Engineers instead package "rotate by θ" into a single object, a **rotation matrix**, that can be applied, combined and undone with simple rules. This lesson builds that object from what you already know.

### Rotating a point, one axis at a time

Take a point p = (x, y) and rotate it anticlockwise about the origin by an angle θ. Where does it go?

The neat way to answer is to think about the two axis directions first.

- The unit vector along x, (1, 0), rotated by θ, lands at **(cos θ, sin θ)**. That is the definition of cosine and sine from the vectors lesson.
- The unit vector along y, (0, 1), starts at 90°. Rotated by θ, it points at 90° + θ, which lands at **(−sin θ, cos θ)**. Check with θ = 90°: (0, 1) should go to (−1, 0), and indeed (−sin 90°, cos 90°) = (−1, 0).

Now, any point is "x steps along the x direction plus y steps along the y direction". Rotation turns the whole plane rigidly, so after rotating, the point is x steps along the *rotated* x direction plus y steps along the *rotated* y direction:

```
x' = x · cos θ − y · sin θ
y' = x · sin θ + y · cos θ
```

That is the whole rule. It looks unfamiliar, but every piece came from the picture of two rotated arrows.

### The rotation matrix

A **matrix** is a rectangular grid of numbers. The rule above is usually written as a 2 × 2 matrix multiplying a column of coordinates:

```
R(θ) = [ cos θ   −sin θ ]
       [ sin θ    cos θ ]

[ x' ]   [ cos θ   −sin θ ] [ x ]
[ y' ] = [ sin θ    cos θ ] [ y ]
```

To multiply a matrix by a column, take each **row** of the matrix in turn, multiply its entries by the matching entries of the column, and add. The first row gives x' = cos θ · x + (−sin θ) · y, the second gives y' = sin θ · x + cos θ · y, exactly as before.

Notice what the **columns** are: the first column is where (1, 0) goes, and the second column is where (0, 1) goes. That is a useful way to read any rotation matrix: its columns are the rotated axes.

### Worked example

Rotate p = (2, 1) by 90°. With cos 90° = 0 and sin 90° = 1:

```
x' = 2 · 0 − 1 · 1 = −1
y' = 2 · 1 + 1 · 0 =  2
```

So (2, 1) goes to (−1, 2). Sketch it: a point to the right and slightly up swings round to the upper left. Now rotate (2, 1) by 30°, with cos 30° ≈ 0.866 and sin 30° = 0.5:

```
x' = 2 · 0.866 − 1 · 0.5 = 1.232
y' = 2 · 0.5   + 1 · 0.866 = 1.866
```

Check the length. Before: √(2² + 1²) = √5 ≈ 2.236. After: √(1.232² + 1.866²) = √(1.518 + 3.482) = √5.000 ≈ 2.236. Rotation never changes the distance from the origin, or the angle between two points. Robots exploit this as a free sanity check.

Here is the same calculation in Python. Remember that Python's trigonometry functions use radians:

```python
import math

def rotate(point, degrees):
    """Rotate a 2D point anticlockwise about the origin."""
    t = math.radians(degrees)
    x, y = point
    return (x * math.cos(t) - y * math.sin(t),
            x * math.sin(t) + y * math.cos(t))

p = (2, 1)
for angle in [90, 30, -30, 360]:
    x, y = rotate(p, angle)
    print(f"{angle:4d} deg: ({x:6.3f}, {y:6.3f})  length {math.hypot(x, y):.3f}")
```

```
  90 deg: (-1.000,  2.000)  length 2.236
  30 deg: ( 1.232,  1.866)  length 2.236
 -30 deg: ( 2.232, -0.134)  length 2.236
 360 deg: ( 2.000,  1.000)  length 2.236
```

A negative angle rotates clockwise, and a full turn brings the point home, as it should.

### Composing rotations

Rotate by 30°, then by 45°. Obviously the total is 75°. The matrix version of "then" is **matrix multiplication**: R(45°) · R(30°). Each entry of the product comes from a row of the first matrix and a column of the second, multiplied and added exactly as before. Working it through numerically gives:

```
R(45°) · R(30°) = [ 0.2588  −0.9659 ]  =  R(75°)
                  [ 0.9659   0.2588 ]
```

and cos 75° ≈ 0.2588, sin 75° ≈ 0.9659. So, in 2D:

```
R(a) · R(b) = R(a + b)
```

This is the matrix form of what you already did in the two-link arm: link 2 points along θ₁ + θ₂ because its rotation is the shoulder's rotation followed by the elbow's.

In 2D, the order of rotations does not matter, because all of them turn about the same axis. **In 3D, order matters.** Hold a book flat, turn it 90° about a vertical axis then 90° about a horizontal axis, and note where it ends up. Start again and do the two turns in the opposite order: the book finishes in a different orientation. That is one reason 3D robotics needs more care, and why getting comfortable with matrices now pays off later.

### Undoing a rotation

To undo a rotation by θ, rotate by −θ. Because cos(−θ) = cos θ and sin(−θ) = −sin θ:

```
R(−θ) = [  cos θ   sin θ ]
        [ −sin θ   cos θ ]
```

This is R(θ) with its rows and columns swapped, called the **transpose**. So for rotation matrices, the inverse is simply the transpose. That is a special and very convenient property: no division, no risk of dividing by zero.

### Rotating points versus rotating frames

This is the idea that causes the most bugs in real robot code, so take it slowly.

There are two different questions that both involve "rotating by θ":

1. **Rotating a point.** The frame stays still and the object moves. "The arm swung 30° anticlockwise; where is the hand now?" Use R(θ).
2. **Rotating a frame.** The object stays still and *you* turn. "My robot is facing 30° anticlockwise from the world's x-axis; where does this fixed object appear in my robot's own coordinates?" Use R(−θ).

Why the opposite sign? Sit in a swivel chair facing a door, then turn 30° to the left. The door has not moved, but from your point of view it is now 30° to your *right*. Turning the observer one way makes the world appear to turn the other way.

### Worked example

A mobile robot sits at the world origin, facing 30° anticlockwise from the world x-axis. Its own frame has x pointing forward and y pointing to its left.

**From robot to world.** Its sensor sees a box 3 m straight ahead: (3, 0) in the robot frame. In world coordinates that is R(30°) applied to (3, 0):

```
x = 3 · 0.866 − 0 · 0.5 = 2.598
y = 3 · 0.5   + 0 · 0.866 = 1.500
```

**From world to robot.** A charging station is at world (4, 2). In the robot frame it is R(−30°) applied to (4, 2):

```
x = 4 · 0.866 + 2 · 0.5   = 4.464
y = −4 · 0.5  + 2 · 0.866 = −0.268
```

So the station is about 4.46 m ahead and 0.27 m to the robot's right (negative y is right). Check it by rotating back with R(30°): you should recover (4, 2). Doing that round trip is the best habit you can build.

### Common mistakes

- **Degrees versus radians**, again. Every trigonometry function in most languages expects radians.
- **The sign of the angle.** Anticlockwise is positive in the standard convention. A different library or sensor may use clockwise; check its documentation.
- **Point versus frame.** Ask "is the thing moving, or am I?" before choosing R(θ) or R(−θ).

### Recap

A 2D rotation by θ sends (x, y) to (x cos θ − y sin θ, x sin θ + y cos θ), written as the matrix R(θ), whose columns are the rotated axes. Rotations preserve lengths. Doing one rotation after another multiplies their matrices, and in 2D the angles simply add. The inverse of a rotation is its transpose, R(−θ). Rotating a point uses R(θ); expressing a fixed point in a frame that has turned by θ uses R(−θ).

#### Project: Paper or Python project: rotate a shape

Draw a small triangle on squared paper with corners at (1, 0), (3, 0) and (3, 2).

1. Rotate each corner by 90° using the rotation rule, and draw the new triangle.
2. Rotate the original by 45°. Use cos 45° = sin 45° ≈ 0.707.
3. Check that each side of the triangle has the same length before and after.
4. Now imagine a robot at the origin facing 90°. Compute where the *original* triangle's corners appear in the robot's own frame, and explain why the answer differs from step 1.

You may use the Python `rotate` function from the lesson to check your hand calculations.

**Deliverables**

- A drawing of the original, 90°-rotated and 45°-rotated triangles
- Side lengths before and after each rotation
- The corners in the robot's frame, with a one-sentence explanation of the sign change

#### Check your understanding

1. Rotating the point (0, 3) by 90° anticlockwise about the origin gives:
   A) (3, 0)
   B) (0, −3)
   C) (−3, 0)
   D) (3, 3)

2. What do the two columns of a 2D rotation matrix represent?
   A) Where the x and y axis directions end up after the rotation
   B) The sine and cosine tables
   C) The original point and the rotated point
   D) The x and y coordinates of the origin

3. Which statement about R(20°) · R(50°) in 2D is correct?
   A) It equals R(1000°)
   B) It equals R(30°)
   C) It depends on which matrix is applied first
   D) It equals R(70°)

4. How can you undo a 2D rotation matrix R(θ) most simply?
   A) Multiply it by 2
   B) Use its transpose, which equals R(−θ)
   C) Divide every entry by θ
   D) Rotations cannot be undone

5. A robot at the origin turns to face 90° anticlockwise. A fixed object is at world (5, 0). Where is it in the robot's own frame (x forward, y left)?
   A) (0, 5)
   B) (0, −5)
   C) (5, 0)
   D) (−5, 0)

**Go further:**

- Wikipedia — Rotation matrix: https://en.wikipedia.org/wiki/Rotation_matrix — The 2D case first, then 3D rotations, with notes on conventions and the point-versus-frame distinction.


## 4.4 Coordinate frames and homogeneous transforms

*Combine rotation and translation into one 3 × 3 matrix, chain transforms from world to base to tool, invert them, and rebuild the two-link arm as a chain of frames.* (about 40 min)

### Many frames, one robot

A real robot cell is full of coordinate frames. The **world frame** is fixed to the room or table. The **base frame** sits at the bottom of the arm. Each link has a frame that moves with it. The **tool frame** is at the gripper's fingertips, and a **camera frame** sits at the camera's lens. Every measurement arrives in some frame: the camera reports where it sees the cup, the joint encoders describe the arm relative to its base, and the task ("put the cup at the corner of the table") is stated in the world frame.

To act, the robot must convert positions between frames quickly and without mistakes. The last lesson handled frames that are rotated relative to each other. Real frames are also **shifted**. This lesson combines both into a single tool, the **homogeneous transform**, and uses it to chain frames together.

### Rotation plus translation

Suppose frame B is rotated by θ relative to frame A, and B's origin sits at position t = (tx, ty) in A. A point whose coordinates in B are p_B has coordinates in A of:

```
p_A = R(θ) · p_B + t
```

Read it as: first rotate the point from B's directions into A's directions, then shift it by where B's origin sits in A.

That works, but chaining several of these by hand gets messy: rotate, add, rotate, add, and the bookkeeping piles up. There is a trick that turns the whole thing into a single multiplication.

### The homogeneous trick

Add a third coordinate, always equal to 1, to every point: (x, y) becomes (x, y, 1). Then build a 3 × 3 matrix with the rotation in the top-left corner and the translation in the right-hand column:

```
T = [ cos θ   −sin θ   tx ]
    [ sin θ    cos θ   ty ]
    [   0        0      1 ]
```

Multiply it by (x, y, 1) using the row-times-column rule, and the first two rows give

```
x_A = cos θ · x − sin θ · y + tx · 1
y_A = sin θ · x + cos θ · y + ty · 1
```

which is exactly rotate-then-shift. The bottom row just keeps the 1 in place. This 3 × 3 matrix is a **homogeneous transform**, and the extra coordinate is called a homogeneous coordinate. The payoff: combining frames is now nothing but matrix multiplication.

### Naming and chaining

A clear naming habit prevents most errors. Write **T_A_B** for the transform that takes coordinates in frame B and gives coordinates in frame A. You can read it as "B as seen from A". Then frames chain like dominoes:

```
T_world_tool = T_world_base · T_base_tool
```

The inner names match (base next to base) and "cancel", leaving world and tool on the outside. If the inner names do not match, the multiplication is a mistake.

### Worked example: the two-link arm as a chain

Recall the arm from the two-link lesson: L₁ = 10 cm, L₂ = 8 cm, θ₁ = 30°, θ₂ = 45°. Using the transforms "Rot(θ)" (rotate only) and "Trans(d)" (shift d along the current x-axis), the hand frame is:

```
T_base_hand = Rot(θ₁) · Trans(L₁) · Rot(θ₂) · Trans(L₂)
```

Read it left to right as instructions to an ant standing at the base: turn by θ₁, walk L₁ along your nose, turn by θ₂, walk L₂. Where the ant ends up is the hand, and the way it faces is the forearm's direction.

Suppose, too, that the gripper's fingertips are 3 cm beyond the end of link 2: add one more Trans(3 cm) to get the tool frame. And suppose the arm is bolted to a table with its base at world position (50, 20) cm, rotated 90° (so the arm's "straight ahead" points along the world's y-axis). Here is the whole chain in Python with the standard library:

```python
import math

def transform(theta_deg, tx, ty):
    """3x3 homogeneous transform: rotate by theta, then shift by (tx, ty)."""
    c, s = math.cos(math.radians(theta_deg)), math.sin(math.radians(theta_deg))
    return [[c, -s, tx], [s, c, ty], [0.0, 0.0, 1.0]]

def matmul(A, B):
    return [[sum(A[i][k] * B[k][j] for k in range(3)) for j in range(3)] for i in range(3)]

def chain(*Ts):
    result = transform(0, 0, 0)          # identity
    for T in Ts:
        result = matmul(result, T)
    return result

L1, L2, tool = 10, 8, 3
T_base_hand = chain(transform(30, 0, 0), transform(0, L1, 0),
                    transform(45, 0, 0), transform(0, L2, 0))
T_base_tool = matmul(T_base_hand, transform(0, tool, 0))
T_world_base = transform(90, 50, 20)
T_world_tool = matmul(T_world_base, T_base_tool)

for name, T in [("hand in base", T_base_hand), ("tool in base", T_base_tool),
                ("tool in world", T_world_tool)]:
    heading = math.degrees(math.atan2(T[1][0], T[0][0]))
    print(f"{name:13s}: ({T[0][2]:6.2f}, {T[1][2]:6.2f}) cm, facing {heading:5.1f} deg")
```

```
hand in base : ( 10.73,  12.73) cm, facing  75.0 deg
tool in base : ( 11.51,  15.63) cm, facing  75.0 deg
tool in world: ( 34.37,  31.51) cm, facing 165.0 deg
```

The first line matches the two-link lesson's answer of (10.73, 12.73), as it must. The position of any frame is the right-hand column of its transform, and its facing direction comes from the first column, via atan2. In the world, the tool faces 75° + 90° = 165°, because the base itself is turned 90°.

Check the last line by hand. Rotating (11.51, 15.63) by 90° gives (−15.63, 11.51); adding the base position (50, 20) gives (34.37, 31.51). It agrees.

### Order matters

Even in 2D, transforms that include translation do **not** commute. Compare two instructions to the ant, starting at the origin facing along x:

- **Rot(90°) then Trans(10):** turn left, then walk 10. The ant ends at (0, 10).
- **Trans(10) then Rot(90°):** walk 10, then turn left. The ant ends at (10, 0), merely facing a new way.

Same pieces, different results. Pure rotations about one point commuted in the last lesson; once frames are shifted, order is everything. Writing the chain as a sentence ("turn, walk, turn, walk") is a reliable way to get the order right.

### Going backwards: the inverse transform

Often you need the opposite direction. A camera fixed above the table reports a cup at world position (38, 32) cm. Where is that in the arm's base frame, so the arm can reach for it? You need T_base_world, the inverse of T_world_base.

Undoing "rotate then shift" means "unshift, then unrotate". Because the inverse of a rotation is its transpose, the inverse transform is:

```
T_B_A = [ Rᵀ   −Rᵀ · t ]
        [ 0  0     1   ]
```

For our base (rotated 90°, at (50, 20)), take it in two steps:

```
unshift:   (38, 32) − (50, 20) = (−12, 12)
unrotate:  apply R(−90°): (x, y) → (y, −x)  gives  (12, 12)
```

So the cup is at (12, 12) cm in the base frame. Now the inverse kinematics from the two-link lesson can take over: r² = 12² + 12² = 288, so cos θ₂ = (288 − 100 − 64) / 160 = 0.775 and θ₂ ≈ ±39.19°. A reachable target, with two possible arm shapes.

A quick check is always available: multiply T_world_base by T_base_world and you should get the **identity** matrix, the transform that changes nothing (ones on the diagonal, zeros elsewhere).

### The full pipeline

This example contains the shape of a real pick-up task:

1. The camera measures the cup in the camera frame.
2. A known transform, found by **calibration**, converts that to the world or base frame.
3. Inverse kinematics finds joint angles that put the tool frame at the cup.
4. Forward kinematics, as a chain of transforms, confirms where the tool will really be.

If any transform in the chain is wrong, for instance because the camera was bumped and its calibration is stale, the robot reaches confidently to the wrong place. Many "the robot missed" problems turn out to be a frame error, not a control error.

### Recap

A homogeneous transform packs a rotation and a translation into one 3 × 3 matrix acting on (x, y, 1). Name transforms T_A_B ("B seen from A") and chain them so inner names match. A robot arm's forward kinematics is a chain of rotate-and-walk transforms, and its tool frame is one more step. Order matters whenever translation is involved. The inverse transform unshifts and then unrotates, using Rᵀ and −Rᵀ · t.

> **Into three dimensions.** In 3D the same ideas use a 4 × 4 matrix: a 3 × 3 rotation, a 3-element translation, and a bottom row of 0 0 0 1. Robot software libraries and simulators pass these transforms around constantly, often maintaining a "tree" of frames so any frame can be expressed in any other. Everything in this lesson carries over.

#### Check your understanding

1. Frame B is rotated 0° relative to frame A and its origin is at (4, −1) in A. A point is at (2, 3) in B. Where is it in A?
   A) (6, 2)
   B) (2, 3)
   C) (−2, 4)
   D) (8, −3)

2. Why is a third coordinate equal to 1 added to 2D points in homogeneous transforms?
   A) To store the point's colour
   B) To make the points three-dimensional
   C) So that the translation column is multiplied by 1 and added, letting rotation and translation be done by a single matrix multiplication
   D) Because rotation matrices need three rows

3. Which chain correctly gives the tool frame in world coordinates?
   A) T_world_tool = T_tool_base · T_world_base
   B) T_world_tool = T_base_world · T_tool_base
   C) T_world_tool = T_base_tool · T_world_base
   D) T_world_tool = T_world_base · T_base_tool

4. Starting at the origin facing along x, an ant does Trans(5) and then Rot(90°). Where is it?
   A) (0, 5)
   B) (5, 0)
   C) (5, 5)
   D) (−5, 0)

5. A robot base is at world (10, 0) with no rotation. A camera sees an object at world (14, 3). Where is the object in the base frame?
   A) (24, 3)
   B) (4, 3)
   C) (−4, −3)
   D) (14, 3)

**Go further:**

- Wikipedia — Transformation matrix: https://en.wikipedia.org/wiki/Transformation_matrix — Rotation, translation and their combination using homogeneous coordinates, including the 3D 4 × 4 form.
- MIT OpenCourseWare — 2.12 Introduction to Robotics: https://ocw.mit.edu/courses/2-12-introduction-to-robotics-fall-2005/ — University lecture notes that build robot kinematics from chains of homogeneous transforms.


## 4.5 Inverse kinematics and the workspace

*Use the two-link inverse kinematics solution like an engineer: map the workspace, choose between multiple solutions, handle unreachable targets and recognise singularities.* (about 40 min)

### From a formula to a decision

In the two-link arm lesson you derived the inverse kinematics (IK) of a planar arm: given a target (x, y), find joint angles θ₁ and θ₂. That formula is the start of the job, not the end. A real robot asking "how do I reach there?" must also decide *which* answer to use when there are two, what to do when there are none, how joint limits change the picture, and why some targets cause wild, fast joint motions. This lesson turns the formula into a working decision procedure.

As a reminder, for links L₁ and L₂ and a target at distance r from the base:

```
cos θ₂ = (r² − L₁² − L₂²) / (2 · L₁ · L₂)
θ₂ = ± arccos(cos θ₂)
θ₁ = atan2(y, x) − atan2(L₂ · sin θ₂, L₁ + L₂ · cos θ₂)
```

Throughout this lesson we use the explorer's default arm: **L₁ = 20 cm** and **L₂ = 15 cm**, with a reach from **5 cm** (|20 − 15|) to **35 cm** (20 + 15).

### Two answers: elbow up and elbow down

Take the target (22, 18), at distance r ≈ 28.43 cm. Then cos θ₂ ≈ 0.305 and θ₂ ≈ ±72.24°. The two complete solutions are:

```
elbow down:  θ₁ ≈  9.12°,  θ₂ ≈ +72.24°
elbow up:    θ₁ ≈ 69.46°,  θ₂ ≈ −72.24°
```

Both put the hand exactly on the target. Geometrically they are mirror images: the elbow sits on one side or the other of the straight line from the base to the target. (Which one gets called "up" is a naming convention; the explorer calls positive θ₂ "elbow down" and negative θ₂ "elbow up".)

Try it now. Switch the explorer to **Inverse**, set the target near (22, 18) and flip between the two elbow solutions.

> **Interactive:** In Inverse mode, drag the target around and switch between elbow up and elbow down. Push the target outside 35 cm and inside 5 cm and read the explanation. Then watch the |sin θ2| reading as you move the target towards the outer edge. Try it at https://tactiverge.win/academy/lab/#kinematics

### Choosing between solutions

Which solution should the robot use? There is no single right answer, but there are standard rules:

1. **Respect joint limits.** If one solution needs an angle the joint cannot physically reach, discard it.
2. **Avoid collisions.** If one elbow position would hit the table, a wall or the robot's own body, discard it.
3. **Move as little as possible.** Among what remains, prefer the solution closest to the arm's current angles. This keeps motion short and smooth and avoids the arm suddenly "flipping" its elbow through a large swing.

Here is a small Python IK solver that returns every solution, plus a chooser that applies rule 3:

```python
import math

def solve_ik(L1, L2, x, y):
    """Return a list of (theta1, theta2) solutions in degrees (may be empty)."""
    c2 = (x * x + y * y - L1 * L1 - L2 * L2) / (2 * L1 * L2)
    if c2 > 1 or c2 < -1:
        return []                                  # out of reach
    solutions = []
    for sign in (+1, -1):                          # elbow down, elbow up
        t2 = sign * math.acos(c2)
        t1 = math.atan2(y, x) - math.atan2(L2 * math.sin(t2), L1 + L2 * math.cos(t2))
        solutions.append((math.degrees(t1), math.degrees(t2)))
    return solutions

def closest(solutions, current):
    """Pick the solution needing the least total joint movement."""
    return min(solutions, key=lambda s: abs(s[0] - current[0]) + abs(s[1] - current[1]))

L1, L2 = 20, 15
for target in [(22, 18), (34, 0), (34.9, 0), (40, 10), (3, 2)]:
    sols = solve_ik(L1, L2, *target)
    shown = ", ".join(f"({a:6.2f}, {b:6.2f})" for a, b in sols) or "unreachable"
    print(f"target {target}: {shown}")

a, b = closest(solve_ik(L1, L2, 22, 18), current=(60, -60))
print(f"closest to (60, -60): ({a:.2f}, {b:.2f})")
```

```
target (22, 18): (  9.12,  72.24), ( 69.46, -72.24)
target (34, 0): (-11.85,  27.75), ( 11.85, -27.75)
target (34.9, 0): ( -3.75,   8.75), (  3.75,  -8.75)
target (40, 10): unreachable
target (3, 2): unreachable
closest to (60, -60): (69.46, -72.24)
```

If the arm is currently at (60°, −60°), the elbow-up solution needs only about 9° and 12° of joint motion, while elbow-down would need about 51° and 132°. The chooser picks elbow up. (A real solver would also wrap angle differences, so that 179° and −179° count as 2° apart, not 358°.)

### Unreachable targets

The solver returns nothing for (40, 10) and (3, 2). The first is r ≈ 41.23 cm from the base, beyond the 35 cm reach, about 6.2 cm too far. The second is r ≈ 3.61 cm, inside the 5 cm hole where the forearm cannot fold back far enough.

What should the robot *do*? Silently returning garbage is the worst option. Sensible responses include:

- **Refuse and report** ("target out of reach"), so the planner can choose another target or move the robot's base.
- **Go to the nearest reachable point**, if getting close is useful. The explorer does this: the arm stretches towards the target and reports how far short it stops.

Either is reasonable; what matters is that the choice is deliberate and visible.

### How joint limits reshape the workspace

The ideal workspace is a ring between 5 and 35 cm. Real joints have limits. Suppose the elbow can only bend from 0° to +150°. Two things change:

1. Only the elbow-down family of solutions (positive θ₂) is available.
2. The arm cannot fold completely. At θ₂ = 150°, the hand's distance from the base is √(L₁² + L₂² + 2 · L₁ · L₂ · cos 150°) = √(400 + 225 − 519.6) ≈ 10.27 cm. The unreachable hole grows from 5 cm to about 10.3 cm.

Shoulder limits, in turn, cut slices out of the ring. Mapping the real workspace, with limits included, is one of the first things engineers do when placing a robot in a work cell.

### Singularities: where the two solutions meet

Look again at the solver output for targets on the x-axis:

- At (34, 0), θ₂ = ±27.75°.
- Move 0.9 cm further out to (34.9, 0), and θ₂ = ±8.75°.

A 0.9 cm move of the target demanded a **19° change** of the elbow. Compare a target well inside the workspace: moving from (30, 0) to (30.9, 0) changes θ₂ from 62.72° to 56.65°, about 6°. Near the outer edge, the arm is nearly straight, and small target changes need large joint changes.

At the very edge (r = 35 cm) the two solutions merge into one, θ₂ = 0, and the arm is fully stretched. The same happens at the inner edge, fully folded. These configurations are called **singularities**. At a singularity the arm loses the ability to move its hand in some direction: stretched out straight, it simply cannot move its hand further outward, no matter how fast the joints turn. Near a singularity it *can* move that way, but only with very large joint speeds.

The explorer's **|sin θ₂|** reading measures how close you are. It is 0 when the arm is straight or folded and 1 when the elbow is at a right angle. The next lesson shows exactly where that number comes from, and why it controls how joint speeds turn into hand speed.

### Beyond two links

With three links in a plane, a target position no longer pins down the joint angles: the third joint adds an extra degree of freedom, so there are infinitely many solutions. The explorer's 3-link mode resolves this by asking you to fix the tool's angle φ, which turns the problem back into a two-link problem for the wrist. Real six-joint arms have closed-form solutions for their particular geometry, or use **numerical IK**: start from a guess, compute how far the hand is from the target, nudge the joints to reduce that error, and repeat. Whichever method is used, the questions from this lesson remain: how many solutions, which one, and what if there are none?

### Recap

A reachable target generally has two IK solutions, elbow up and elbow down. Choose between them using joint limits, collisions and the least movement from the current pose. Targets outside the outer radius or inside the inner hole have no solution; handle them deliberately. Joint limits shrink and reshape the workspace. At the workspace edges, the solutions merge at singularities, where the arm cannot move in some direction and nearby targets demand large joint motions.

#### Project: Explorer and Python project: a reachability report

Using the explorer's default arm (L₁ = 20 cm, L₂ = 15 cm):

1. Choose eight targets: three well inside the workspace, two within 1 cm of the outer edge, one within 1 cm of the inner edge, and two unreachable.
2. For each, record both solutions from the explorer, or from the Python solver, and verify one of them with forward kinematics.
3. Assume the arm currently sits at θ₁ = 0°, θ₂ = 90°. For each reachable target, say which solution the "least movement" rule picks.
4. Now impose an elbow limit of 0° to +150°. Which of your targets become unreachable, and why?

No hardware is needed.

**Deliverables**

- A list of eight targets with r, cos θ₂ and both solutions (or 'unreachable')
- One forward-kinematics check per reachable target
- The chosen solution for each target and the effect of the elbow limit

#### Check your understanding

1. An arm has L₁ = 20 cm and L₂ = 15 cm. Which target has no inverse kinematics solution?
   A) (20, 10)
   B) (0, 30)
   C) (4, 2)
   D) (−25, 0)

2. Two valid solutions reach a target. The arm is currently close to the elbow-up solution. Which is usually preferred, assuming both respect joint limits and avoid collisions?
   A) Elbow up, because it needs less joint movement from the current pose
   B) Elbow down, because it is always safer
   C) Whichever has the larger θ₁
   D) Neither; the robot should refuse the target

3. With the elbow limited to 0°…+150° on a 20 cm / 15 cm arm, the inner unreachable radius is about:
   A) 5 cm
   B) 35 cm
   C) 0 cm
   D) 10.3 cm

4. What happens to the two IK solutions as a target approaches the outer edge of the workspace?
   A) They move further apart
   B) They merge into one solution with the arm fully stretched, a singular configuration
   C) A third solution appears
   D) They become negative

5. Why do targets near a singularity cause problems for a robot controller?
   A) The target becomes invisible to the camera
   B) Forward kinematics stops working
   C) Small changes in the target require large changes in joint angles, which means very fast joint motion
   D) The gripper opens automatically

**Go further:**

- Wikipedia — Inverse kinematics: https://en.wikipedia.org/wiki/Inverse_kinematics — Analytical and numerical approaches to IK, with examples beyond two links.


## 4.6 Velocity kinematics and the Jacobian

*How joint speeds become hand speed: build the planar two-link Jacobian from the idea of rotating points, check it numerically, and see why singular configurations make the hand stuck.* (about 40 min)

### From where to how fast

So far we have asked *where* the hand is. Many tasks care just as much about *how it moves*. A robot drawing a straight line, gluing along a seam, or sliding a tray across a table must keep its hand moving in a chosen direction at a chosen speed. That means converting between **joint speeds** (how fast each joint turns, in radians per second) and **hand velocity** (how fast, and which way, the hand moves, in cm/s). The tool that does this is the **Jacobian**, and it also explains the singularities you met in the last lesson.

A note on notation: engineers write a dot over a quantity to mean "how fast it is changing". So θ̇₁ ("theta-one-dot") is the shoulder's angular speed and ẋ is how fast the hand's x coordinate is changing. You do not need calculus for this lesson; the ideas come from circles.

### One link: speed equals angular speed times radius

Spin a single link of length L about its joint at angular speed ω (omega), in rad/s. The tip moves around a circle, always **perpendicular** to the link. Its speed is:

```
v = ω × L
```

This simple formula only works with ω in radians per second. That is the deep reason radians are used: one radian of rotation moves a point exactly one radius along the circle. A 10 cm link turning at 0.5 rad/s moves its tip at 5 cm/s.

There is a tidy way to get the direction too. If the vector from the pivot to the point is (a, b), then the point's velocity is that vector rotated by 90° and scaled by ω:

```
velocity = ω × (−b, a)
```

Rotating by 90° is the R(90°) rule from the rotations lesson: (a, b) becomes (−b, a).

### Two links: add the contributions

Now the two-link arm. Each joint's motion contributes some hand velocity, and the contributions simply add.

- **Shoulder turning at θ̇₁** swings the *whole* arm about the base. The hand moves as a point at the end of the vector from the base to the hand, (x, y). Its contribution is θ̇₁ × (−y, x).
- **Elbow turning at θ̇₂** swings only the forearm, about the elbow. The vector from elbow to hand is (L₂ cos(θ₁ + θ₂), L₂ sin(θ₁ + θ₂)). Its contribution is θ̇₂ times that vector rotated by 90°.

Writing s₁ = sin θ₁, c₁ = cos θ₁, s₁₂ = sin(θ₁ + θ₂) and c₁₂ = cos(θ₁ + θ₂), and adding:

```
ẋ = −(L₁·s₁ + L₂·s₁₂) · θ̇₁ − L₂·s₁₂ · θ̇₂
ẏ =  (L₁·c₁ + L₂·c₁₂) · θ̇₁ + L₂·c₁₂ · θ̇₂
```

The four coefficients form a 2 × 2 matrix, the **Jacobian** J:

```
J = [ −L₁·s₁ − L₂·s₁₂    −L₂·s₁₂ ]
    [  L₁·c₁ + L₂·c₁₂     L₂·c₁₂ ]

[ ẋ ]       [ θ̇₁ ]
[ ẏ ] = J · [ θ̇₂ ]
```

Read it by columns, just as you read rotation matrices: **column 1** is the hand velocity produced by turning only the shoulder at 1 rad/s; **column 2** is the hand velocity produced by turning only the elbow at 1 rad/s. Any combination of joint speeds produces a mix of those two columns.

Unlike a rotation matrix, the Jacobian **changes as the arm moves**, because it depends on θ₁ and θ₂. It describes how the arm can move *right now*, in its current pose.

### Worked example

Use the familiar arm: L₁ = 10 cm, L₂ = 8 cm, θ₁ = 30°, θ₂ = 45°, with the hand at (10.73, 12.73). Then:

```
J ≈ [ −12.727   −7.727 ]
    [  10.731    2.071 ]
```

The first column is (−y, x) for the hand, as expected. Now try three sets of joint speeds:

```
θ̇ = (0.5, 0)    → hand velocity (−6.364, 5.365) cm/s, speed 8.32 cm/s
θ̇ = (0, 1)      → hand velocity (−7.727, 2.071) cm/s, speed 8.00 cm/s
θ̇ = (0.5, −0.5) → hand velocity (−2.500, 4.330) cm/s, speed 5.00 cm/s
```

Each result can be understood without the matrix:

- Shoulder only at 0.5 rad/s: the hand is 16.65 cm from the base, and 0.5 × 16.65 ≈ 8.32 cm/s.
- Elbow only at 1 rad/s: the hand is 8 cm from the elbow, so it moves at 1 × 8 = 8 cm/s.
- Shoulder +0.5 and elbow −0.5: the forearm's absolute angle θ₁ + θ₂ stays fixed, so the forearm slides along without turning and the hand moves exactly like the elbow: 0.5 × 10 = 5 cm/s.

### Check it numerically

A good engineer never trusts a derived formula without an independent test. Here, the test is to take a tiny time step, move the joints a tiny amount, recompute the hand position with forward kinematics, and divide the change by the time:

```python
import math

L1, L2 = 10, 8

def fk(t1, t2):
    return (L1 * math.cos(t1) + L2 * math.cos(t1 + t2),
            L1 * math.sin(t1) + L2 * math.sin(t1 + t2))

def jacobian(t1, t2):
    s1, c1 = math.sin(t1), math.cos(t1)
    s12, c12 = math.sin(t1 + t2), math.cos(t1 + t2)
    return [[-L1 * s1 - L2 * s12, -L2 * s12],
            [ L1 * c1 + L2 * c12,  L2 * c12]]

t1, t2 = math.radians(30), math.radians(45)
rate1, rate2 = 0.5, 0.0                  # joint speeds in rad/s

J = jacobian(t1, t2)
vx = J[0][0] * rate1 + J[0][1] * rate2
vy = J[1][0] * rate1 + J[1][1] * rate2
print(f"Jacobian:      ({vx:.3f}, {vy:.3f}) cm/s")

dt = 0.0001                              # a tiny time step, in seconds
x0, y0 = fk(t1, t2)
x1, y1 = fk(t1 + rate1 * dt, t2 + rate2 * dt)
print(f"tiny step:     ({(x1 - x0) / dt:.3f}, {(y1 - y0) / dt:.3f}) cm/s")
```

```
Jacobian:      (-6.364, 5.365) cm/s
tiny step:     (-6.364, 5.365) cm/s
```

They agree to three decimal places. This "finite difference" check is how engineers test Jacobians in real robot software too.

### Going backwards: joint speeds for a desired hand velocity

The useful direction is usually the reverse: "I want the hand to move at (ẋ, ẏ); how fast should each joint turn?" That means solving two equations for two unknowns. For a 2 × 2 matrix with entries J₁₁, J₁₂ (top row) and J₂₁, J₂₂ (bottom row), the solution is:

```
det = J₁₁·J₂₂ − J₁₂·J₂₁
θ̇₁ = ( J₂₂·ẋ − J₁₂·ẏ) / det
θ̇₂ = (−J₂₁·ẋ + J₁₁·ẏ) / det
```

The number **det** is the **determinant**. For the two-link arm, the algebra simplifies beautifully:

```
det = L₁ · L₂ · sin θ₂
```

For our example, det = 10 × 8 × sin 45° ≈ 56.57.

### Singular configurations

Look at what happens when sin θ₂ = 0, that is, θ₂ = 0° (arm straight) or 180° (arm folded). The determinant is zero, and the formulas above would divide by zero. That is the mathematical face of a **singularity**.

The physical picture is clearer. With the arm straight, both columns of J point in the same direction, perpendicular to the arm. Turning the shoulder moves the hand sideways; turning the elbow also moves the hand sideways. *Neither* joint can move the hand along the arm's own line, so radial motion is impossible.

Just before a singularity, motion is possible but expensive. With the shoulder at θ₁ = 0°, ask the hand to move at 1 cm/s in the −x direction (back towards the base), and compare the joint speeds this needs in poses where the elbow is closer and closer to straight:

```
θ₂      det     θ̇₁ (deg/s)   θ̇₂ (deg/s)
90°    80.00       0.00          7.16
30°    40.00      −9.92         24.25
 5°     6.97     −65.49        147.66
 1°     1.40    −328.25        738.62
```

The hand speed requested never changes, yet the joint speeds explode as the arm straightens. A real controller following a path near a singularity would hit its motor speed limits, jerk, or behave erratically. Practical responses include slowing the hand down near singularities, planning paths that stay away from them, and using modified solvers that accept a small path error in exchange for sane joint speeds.

This is what the explorer's **|sin θ₂|** reading measures: how far the arm is from singular. Near 1 (elbow at a right angle), the arm is as far from singular as it can be, and both joints can move the hand in any direction without huge joint speeds. (Whether every direction is equally easy also depends on the link lengths.) Near 0, some direction is almost lost.

> **Interactive:** In Forward mode, set θ2 to 90° and then slowly reduce it towards 0°. Watch |sin θ2| fall and imagine trying to move the hand straight towards the base. Repeat with θ2 near 180°, the folded singularity. Try it at https://tactiverge.win/academy/lab/#kinematics

### A glimpse further: forces

The Jacobian has a second job. The same matrix, transposed, converts a force at the hand into the joint torques needed to resist it. One consequence feels surprising at first: near a straight-arm singularity, the arm can resist a large push along its own length with almost no joint torque, because the links themselves carry the load. You will meet this force relationship in more advanced courses; for now, notice that one matrix links speeds and forces.

### Recap

A point rotating at ω about a pivot moves at ω × distance, perpendicular to the line from the pivot, with ω in rad/s. For a two-link arm, the hand velocity is the sum of the shoulder's and elbow's contributions, written as J times the joint speeds. The Jacobian's columns are the hand velocities from each joint alone, and J changes with the pose. Its determinant, L₁ · L₂ · sin θ₂, is zero when the arm is straight or folded: a singularity, where some hand direction is impossible and nearby motions need huge joint speeds.

#### Check your understanding

1. A 12 cm link rotates at 0.25 rad/s. How fast does its tip move?
   A) 48 cm/s
   B) 3 cm/s
   C) 0.25 cm/s
   D) 12.25 cm/s

2. What does the first column of the two-link Jacobian represent?
   A) The hand's position
   B) The elbow's position
   C) The joint angles
   D) The hand velocity produced by turning only the shoulder at 1 rad/s

3. For a two-link arm with L₁ = 10 cm and L₂ = 8 cm at θ₂ = 30°, what is the Jacobian's determinant?
   A) 80
   B) 69.3
   C) 40
   D) 0

4. Why can a fully straight two-link arm not move its hand directly towards the base?
   A) Both Jacobian columns point the same way, perpendicular to the arm, so no combination of joint speeds produces motion along the arm
   B) The motors are switched off at full reach
   C) The determinant is very large
   D) The hand is outside the workspace

5. A shoulder turns at +0.4 rad/s while the elbow turns at −0.4 rad/s. What is true of the forearm?
   A) It rotates twice as fast as the shoulder
   B) Its absolute direction θ₁ + θ₂ stays constant, so the hand moves exactly like the elbow
   C) It stops the whole arm moving
   D) It moves the hand along the arm's line

**Go further:**

- Wikipedia — Jacobian matrix and determinant: https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant — The general mathematical idea behind the robot Jacobian. Uses calculus notation, so treat it as a look ahead.


---

# Module 5: Introduction to feedback control

How machines use measurements of their own behaviour to correct themselves, from simple on–off thermostats to proportional controllers and their limits.

**Objectives**

- Distinguish open-loop from closed-loop control using everyday examples.
- Identify the set point, measurement, error and control action in a feedback loop.
- Predict how changing a proportional gain affects speed, overshoot and stability.
- Explain steady-state error and why integral action can remove it.


## 5.1 Open loop and closed loop

*Why measuring the result changes everything: the parts of a feedback loop and the simplest controller of all, on–off control.* (about 25 min)

### Two ways to make toast

Imagine two toasters. The first has a timer: you set it to three minutes and it heats for three minutes, no matter what. The second has a sensor that watches the colour of the bread and stops when it reaches the shade you chose.

The first toaster works well when everything is as expected. But if the bread is frozen, it comes out pale; if the bread is thin, it burns. The timer has no way of knowing. The second toaster does not care whether the bread is frozen or thin — it keeps heating until the *result* is right.

These are the two fundamental approaches to control:

- **Open-loop control** decides what to do in advance and does it, without measuring the result. The timer toaster, a basic microwave, and a sprinkler on a timer are all open-loop.
- **Closed-loop control**, also called **feedback control**, measures the result and uses that measurement to adjust what it does. The colour-sensing toaster, a home thermostat and your own hand reaching for a glass are all closed-loop.

### The parts of a feedback loop

Every feedback loop has the same ingredients, whatever it controls. Using a home heating system as the example:

- **Set point (or reference):** the value you want. Say, 20 °C.
- **Measurement:** what a sensor says the value actually is. A thermometer reads 17 °C.
- **Error:** the set point minus the measurement. Here, 20 − 17 = **+3 °C**. A positive error means "too low"; a negative error means "too high".
- **Controller:** the rule that turns the error into an action.
- **Actuator:** the device that carries out the action — the boiler or heater.
- **Plant (or process):** the thing being controlled. Here, the room and the air in it.
- **Disturbances:** outside influences you do not control — an open window, a sunny afternoon, people coming in.

The loop runs continuously: measure, compute the error, act, let the room respond, measure again. The great strength of feedback is that the controller does not need to know *why* the room is cold. An open window and a cold morning look the same to it: both produce an error, and it responds to the error.

### Why not just plan carefully?

You might wonder why we do not simply build a very accurate model of the room and calculate exactly how long to run the heater, open-loop. Sometimes that works, and good engineers use models wherever they help. But open-loop control has two weaknesses that feedback addresses:

1. **Models are never perfect.** The room's insulation, the heater's power and the outside temperature are all known only approximately.
2. **Disturbances are unpredictable.** Nobody can model in advance when a door will be left open.

Feedback copes with both, because it reacts to what is actually happening. This is the same reason a robot keeps sensing even after it has made a plan, as discussed in the introduction to robotics.

### The simplest controller: on–off

The most basic controller has only two outputs: fully on or fully off. Older thermostats work this way. The rule is:

- If the temperature is below the set point, turn the heater on.
- If it is above, turn it off.

This is called **on–off control** or **bang–bang control**. It is cheap and robust, but it has a problem. Heating systems take time to respond — the heater warms up, the warm air spreads, the thermometer catches up. By the time the thermometer reads 20 °C and the heater switches off, there is still heat on its way, so the temperature continues rising past 20. Then it falls below 20, the heater switches on, and the lag carries it too low. The temperature ends up **oscillating** around the set point instead of settling on it.

Worse, if the measurement is very close to the set point, sensor noise can make the heater switch on and off many times per second. That wears out switches and motors. The usual fix is **hysteresis**: use a small band around the set point. For example, switch on below 19.5 °C and off above 20.5 °C. The temperature still wanders within the band, but the switching becomes calm and predictable.

### Feedback in robots

A robot joint is a feedback problem too. The set point is the angle you want, a sensor such as an encoder measures the actual angle, and the motor is the actuator. If the controller is on–off — full power one way or the other — the joint overshoots, reverses and overshoots again, a jittery motion you may have seen in hobby projects. To get smooth, accurate motion, a controller needs to act more gently when the error is small. That is exactly what proportional control, the subject of the next lesson, provides.

> **Spot the loop.** Feedback is everywhere once you look. When you carry a full cup of tea, your eyes watch the surface and your hand makes tiny corrections. Your body keeps its temperature near 37 °C by sweating or shivering. Try listing three loops in your day, naming the set point, the sensor and the actuator for each.

#### Check your understanding

1. Which of these is an example of open-loop control?
   A) A garden sprinkler that runs for 20 minutes every evening, whatever the weather
   B) A thermostat switching a heater based on room temperature
   C) A cruise-control system that adjusts the throttle to hold a speed
   D) A person steering a bicycle to stay on a path

2. The set point is 50 and the measurement is 62. What is the error?
   A) −12
   B) +12
   C) 112
   D) 0

3. Why does a simple on–off heater cause the temperature to oscillate around the set point?
   A) Because the heater is broken
   B) Because thermometers cannot read decimals
   C) Because the set point keeps changing
   D) Because the system responds with a delay, so it keeps rising after switch-off and keeps falling after switch-on

4. What is the main purpose of adding hysteresis to an on–off controller?
   A) To make the controller open-loop
   B) To remove the need for a sensor
   C) To stop rapid on–off switching caused by noise near the set point
   D) To make the temperature exactly equal the set point


## 5.2 Proportional control and its limits

*Act in proportion to the error: how the gain trades speed for stability, why a steady error can remain, and the ideas behind integral and derivative action.* (about 40 min)

### Gentler when close, stronger when far

When you park a bicycle against a wall, you do not ride at full speed and then slam the brakes. You slow down as you get closer. That is the intuition behind **proportional control**: make the action proportional to the error.

```
action = Kp · error
```

**Kp** is called the **proportional gain**. It is a number you choose. A large gain means "react strongly to any error"; a small gain means "react gently". When the error is large, the action is large. As the error shrinks, the action shrinks with it, so the system eases into the set point instead of crashing past it — at least, that is the hope.

### A model simple enough to compute by hand

To see what the gain does, we will use a deliberately simple model. A robot moves along a line. Its position is measured once per time step. At each step, the controller computes the error and moves the robot by Kp times that error. In symbols, with set point 100:

```
error = 100 − position
position_next = position + Kp · error
```

Each step closes a fraction Kp of the remaining gap. Start every run at position 0.

### Kp = 0.5

```
step 0:   0.0
step 1:  50.0
step 2:  75.0
step 3:  87.5
step 4:  93.75
step 5:  96.875
```

Each step halves the error. The robot approaches 100 smoothly and never overshoots. It is stable, but it takes a while.

### Kp = 1.0

```
step 0:   0
step 1: 100
```

It closes the whole gap in a single step. In this idealized model, that is perfect. Real systems are never this clean, as you will see.

### Kp = 1.5

```
step 0:   0.0
step 1: 150.0
step 2:  75.0
step 3: 112.5
step 4:  93.75
step 5: 103.125
```

Now it **overshoots**: it jumps past 100, then comes back too far, and so on. The swings shrink each time, so it does settle, but the motion is wobbly.

### Kp = 2.0 and beyond

With Kp = 2 the position goes 0, 200, 0, 200, … forever: a sustained oscillation. With Kp = 2.5 it goes 0, 250, −125, 437.5, … — each swing is *larger* than the last. The system is **unstable**. A real robot doing this would hit its limits or break something.

### What the example teaches

This toy model captures the central trade-off of feedback control:

- **Low gain:** stable and smooth, but slow.
- **Higher gain:** faster, but overshoot appears.
- **Too high a gain:** oscillation, then instability.

In real machines, the trouble usually comes from **delay** and **inertia**. A motor cannot change speed instantly, and a sensor reading is always slightly old. The controller is steering using a picture of the recent past, so an aggressive response arrives too late and too strongly. This is why the perfect Kp = 1 result is fragile: add a little delay to the model and it starts to overshoot too.

### Try it yourself

The explorer below simulates a feedback loop. Raise and lower the gain and watch how quickly the response rises, how far it overshoots and whether it settles. Look for the gain where the response first starts to overshoot, and the point where it stops settling at all.

> **Interactive:** Adjust the controller gain and watch the response. Find a setting that is fast without overshooting much, then push it until the loop becomes unstable. Try it at https://tactiverge.win/academy/lab/#feedback

### The stubborn leftover error

Now add something realistic: a constant **disturbance**. Suppose the robot sits on a slight slope, so that every step it slides back 5 units regardless of what the controller does.

```
position_next = position + Kp · error − 5
```

With Kp = 0.5, where does the robot end up? It stops changing when the controller's push exactly cancels the slide:

```
Kp · error = 5
error = 5 / 0.5 = 10
```

The robot settles at **90**, not 100. A permanent gap like this is called **steady-state error**. It happens because a proportional controller *needs* an error to produce any action at all. If the error were zero, the action would be zero, and the slope would win.

Doubling the gain to Kp = 1 halves the steady-state error to 5. But, as we saw, raising the gain eventually causes overshoot and instability. Proportional control alone cannot remove the error completely.

### Integral and derivative: the ideas

Engineers solved this long ago by adding two more terms. You will meet the details later; here is the intuition.

**Integral action** keeps a running total of past error. While even a small error persists, the total keeps growing, and so does its push. It only stops growing when the error is truly zero. This is what removes steady-state error: on the slope, the integral term gradually builds up exactly the push needed to hold the robot at 100. The cost is that a large stored total can cause overshoot of its own.

**Derivative action** looks at how fast the error is changing. If the robot is rushing towards the set point, the derivative term applies the brakes *before* it arrives, reducing overshoot. Its weakness is noise: a jittery sensor reading looks like rapid change, so derivative action is usually filtered.

Put together, the three terms form the **PID controller** — proportional, integral, derivative:

```
action = Kp · error + Ki · (sum of past error) + Kd · (rate of change of error)
```

PID controllers are among the most widely used control algorithms in engineering, found in everything from drones and 3D printers to industrial processes. Choosing the three gains, called **tuning**, is a skill that combines mathematics, simulation and careful experiment.

> **Report what the system actually did.** When you tune a controller, it is tempting to show only the one run that looked best. Honest engineering reports how the controller behaves across many runs and conditions, including the ones where it overshoots or fails. A controller that works once on a good day is not yet a working controller.

#### Project: Paper or spreadsheet project: tune a controller

Using the model `position_next = position + Kp · (100 − position) − d`, explore by hand, with a spreadsheet, or with a short program:

1. With d = 0, compute ten steps for Kp = 0.3, 0.8, 1.2 and 1.9. Plot all four on one graph.
2. Repeat with d = 5. For each gain, predict the final position using error = d / Kp, then check your prediction against the computed values.
3. Write a short paragraph recommending a gain, and explain the trade-off you made between speed, overshoot and steady-state error.

No hardware is needed for this project.

**Deliverables**

- A table or plot of ten steps for each gain, with and without disturbance
- Predicted versus computed steady-state values
- A justified gain recommendation in one paragraph

#### Check your understanding

1. In the model position_next = position + Kp · (100 − position), starting from 0, where is the robot after one step with Kp = 0.4?
   A) 4
   B) 40
   C) 60
   D) 100

2. As you steadily increase a proportional gain on a real system with some delay, what typically happens?
   A) The response gets slower and smoother
   B) The response gets faster, then starts to overshoot, and eventually becomes unstable
   C) Nothing changes
   D) The steady-state error grows

3. With a constant disturbance d = 6 and Kp = 0.3, what steady-state error does the simple model predict?
   A) 1.8
   B) 6
   C) 20
   D) 0

4. Why can a proportional controller alone not eliminate steady-state error against a constant disturbance?
   A) Because proportional controllers are open-loop
   B) Because sensors cannot measure small errors
   C) Because the gain is always less than 1
   D) Because its action is zero when the error is zero, so some error must remain to push against the disturbance

5. What does integral action contribute to a PID controller?
   A) It accumulates past error so that persistent error keeps increasing the push until it is removed
   B) It predicts future error to reduce overshoot
   C) It filters sensor noise
   D) It replaces the sensor

**Go further:**

- MIT OpenCourseWare — 2.14 Analysis and Design of Feedback Control Systems: https://ocw.mit.edu/courses/2-14-analysis-and-design-of-feedback-control-systems-spring-2014/ — A university course that develops these ideas with full mathematics. Useful as a map of where feedback control goes next.


## 5.3 Integral action and steady-state error

*Why a proportional controller always leaves a gap against a steady load, how adding up past error closes that gap, and the overshoot you pay for it.* (about 30 min)

### The gap that will not close

Picture a robot arm holding a heavy tool out to the side. Gravity pulls the joint down all the time, so the motor has to push all the time just to stay still. In the last lesson you saw what a proportional controller does in this situation: it settles with a small, permanent error. The arm sags a little below the angle you asked for, because a P controller only pushes when there is an error to push against.

For many jobs a small sag is fine. For a robot placing a part into a hole, a drone holding its height against its own weight, or an oven holding a temperature while heat leaks out of its walls, it is not. This lesson adds the second term of the PID controller, **integral action**, which is the standard way to remove that leftover error.

### Why P alone must leave an error

Recall the toy model from the proportional lesson. A robot on a slope moves, each time step, by the controller's action minus a slide of 5 units:

```
error = 100 − position
position_next = position + Kp · error − 5
```

The robot stops moving when the controller's push exactly cancels the slide, Kp · error = 5. With Kp = 0.5, that needs an error of 10, so it parks at 90. Raising Kp shrinks the gap but never removes it, and raising Kp too far causes oscillation.

The same thing happens in continuous systems. For a plant with static gain K (its output settles at K times a steady input) under P control with gain Kp, the steady-state error for a set point r is

```
steady-state error = r / (1 + Kp · K)
```

With r = 1, K = 1 and Kp = 2, the error is 1 / 3 ≈ 0.333: the output settles at about 0.667 instead of 1. That is not a bug in the controller. It is a direct consequence of its rule. To hold the output at the set point the plant needs a steady input, and a P controller can only produce a steady input by keeping a steady error.

### A controller with a memory

The fix is to give the controller a memory. As well as the current error, keep a **running total** of every error so far, and add a share of that total to the action:

```
total = total + error            (every step)
action = Kp · error + Ki · total
```

**Ki** is the **integral gain**. The name comes from calculus: adding up error over time is what an integral does. In a continuous controller the total is the area under the error curve, built up as error × time step on each update.

Here is the key idea. While any error remains, the total keeps changing. If the robot is still short of the set point, the total keeps growing, so the push keeps growing. The only way for the total to *stop* changing is for the error to be zero. So if the loop settles at all, it must settle with zero error, and the integral term is left holding exactly the push needed to cancel the load. The proportional term then contributes nothing at rest, because its error is zero; the integral term does all the steady work.

### Worked example: the robot on the slope

Run the toy model with Kp = 0.5 and three integral gains. This listing uses only standard Python:

```python
def run(kp, ki, steps=40, slope=5):
    position = 0.0
    total = 0.0                  # running sum of error
    history = []
    for step in range(steps + 1):
        error = 100 - position
        history.append(position)
        total += error
        position += kp * error + ki * total - slope
    return history

for ki in (0.0, 0.05, 0.1):
    h = run(0.5, ki)
    print(f"Ki={ki:<4}  step 5: {h[5]:6.1f}  step 10: {h[10]:6.1f}"
          f"  step 40: {h[40]:6.1f}  peak: {max(h):6.1f}")
```

Output:

```
Ki=0.0   step 5:   87.2  step 10:   89.9  step 40:   90.0  peak:   90.0
Ki=0.05  step 5:  104.1  step 10:  105.6  step 40:  100.2  peak:  106.4
Ki=0.1   step 5:  115.4  step 10:  107.2  step 40:  100.0  peak:  115.4
```

Three lessons sit in those numbers:

1. **Without integral action** the robot stops at 90, exactly as the formula Kp · error = 5 predicted.
2. **With integral action** it reaches 100. At rest the error is zero, so Ki · total must equal 5. With Ki = 0.1, the total ends at 50; you can check this by printing it.
3. **It overshoots on the way.** With Ki = 0.1 the robot peaks at 115.4 before coming back. More integral gain removes the error faster, but overshoots further.

### Why the integral overshoots

The integral term remembers the past, and the past is not always helpful. On the way up, the error is large and positive for many steps, so the total grows large. When the robot reaches 100, the error is zero, but the total is still large, so the controller is still pushing hard. It goes past the set point. Only once the error turns negative does the total start to shrink, and it takes a while to unwind. That stored push is the overshoot.

A useful picture is filling a bath by watching the water level. If you keep turning the tap further open for as long as the level is low, then by the time it reaches the line the tap is wide open, and the bath overfills before you can turn it back. A gentler integral gain is like turning the tap more slowly: less overfill, but a longer wait.

So the integral gain brings a new trade-off:

- **Too little Ki:** the error disappears, but so slowly that you may run out of patience. A response that is still creeping up after ten seconds is not much better than one with a permanent error.
- **Moderate Ki:** the error goes in a reasonable time with a small overshoot.
- **Too much Ki:** large overshoot, slow-dying oscillation and, in the end, instability.

### Try it in the explorer

The explorer below simulates a first-order plant, such as motor speed or temperature, with gain K = 1 and time constant τ = 1 s, and a set point of 1. Its metrics panel reports rise time, overshoot, settling time and steady-state error.

1. Choose **P** with Kp = 2. The steady-state error reads 0.333, matching r / (1 + Kp · K).
2. Switch to **PI**, keep Kp = 2 and set Ki = 1.5. The error falls to zero, with no overshoot, and the output settles within 2 % after about 3.7 s.
3. Set Ki = 0.5. The output is still creeping towards 1 when the run ends at 10 s: the error is gone in principle but not in practice.
4. Raise Ki to 4, then 10, then 20. Overshoot grows from about 8 % to about 25 % to about 39 %. Rise time shortens, but the response becomes wobbly.
5. Turn on the **load disturbance**. With P control the output drops from 0.667 to 0.533 when the load arrives at 5 s and stays there. With PI (Kp = 2, Ki = 1.5) it dips to about 0.89 and then climbs back towards 1, as the integral rebuilds the push the load took away.

> **Interactive:** Start with P control at Kp = 2 and note the steady-state error. Switch to PI and sweep Ki from 0.5 to 20, watching the error vanish and the overshoot grow. Then turn on the load disturbance and compare how P and PI respond to it. Try it at https://tactiverge.win/academy/lab/#feedback

### Integral action in real robots

Integral action is the reason a well-tuned joint can hold a heavy load at exactly the commanded angle, and why a drone does not slowly sink as its battery voltage falls. Any slow, steady disturbance looks the same to the integrator: a small error that will not go away, which it steadily cancels.

The same memory causes trouble when the controller cannot do what it asks. If a motor is already at full power and the error persists, the integral total keeps growing even though the extra push cannot be delivered. When the error finally reverses, the controller has a huge stored total to unwind and overshoots badly. This is called **integrator windup**, and you will meet it, with its fixes, in the lesson on practical control issues.

### Recap

- A proportional controller needs an error to produce a push, so against a steady load it leaves a steady-state error of r / (1 + Kp · K).
- Integral action adds a running total of past error to the action. The total only stops changing when the error is zero, so a settled PI loop has no steady-state error.
- At rest, the integral term supplies the whole steady push; the proportional term supplies none.
- The cost is overshoot: the stored total keeps pushing after the set point is reached. Too little Ki is slow, too much Ki is oscillatory.
- The derivative term, next, adds a way to brake before the set point arrives.

#### Project: Simulation project: find a good integral gain

Use the Python listing in this lesson, a spreadsheet, or a calculator.

1. With Kp = 0.5 and a slope of 5, run Ki = 0.02, 0.05, 0.1, 0.2 and 0.4 for 60 steps. For each, record the peak position and the first step after which the position stays between 98 and 102.
2. Print the running total at the end of each run and check that Ki × total ≈ 5. Explain in one sentence why this must be true.
3. Change the slope to 10 and repeat for your favourite Ki. Does the final position change? Does the overshoot?
4. Recommend one Ki and justify it in a short paragraph, naming what you gave up.

No hardware is needed for this project.

**Deliverables**

- A table of peak position and settling step for five values of Ki
- The final running totals, with a one-sentence explanation of Ki × total ≈ slope
- A justified recommendation for Ki

#### Check your understanding

1. A first-order plant with K = 1 is under P control with Kp = 4 and set point 1. What steady-state error do you expect?
   A) 0.25
   B) 0.2
   C) 0
   D) 0.8

2. Why does a settled PI controller end with zero error?
   A) Because the integral gain is always larger than the proportional gain
   B) Because the running total only stops changing when the error is zero, so the loop can only come to rest there
   C) Because the integral term switches the proportional term off
   D) Because integral action removes the need for a sensor

3. In a settled PI loop holding a robot arm against gravity, which term supplies the steady push?
   A) The proportional term, because it acts on the error
   B) Both terms equally
   C) Neither: gravity is cancelled by the sensor
   D) The integral term, because the error, and so the proportional term, is zero

4. You raise Ki from 4 to 20 on the explorer's first-order plant. What is the most likely change?
   A) Faster rise but much larger overshoot
   B) Slower rise and no overshoot
   C) A larger steady-state error
   D) No change, because Ki only affects disturbances

5. What causes integrator windup?
   A) Sensor noise being amplified by the integral term
   B) Choosing Ki smaller than Kp
   C) The running total growing while the actuator is already at its limit and cannot deliver more push
   D) Using a first-order plant instead of a second-order one

**Go further:**

- Wikipedia — PID controller: https://en.wikipedia.org/wiki/PID_controller — A thorough reference on the three terms, with sections on integral windup and other practical modifications.


## 5.4 Derivative action and damping

*How reacting to the rate of change lets a controller brake before it overshoots, what under-, over- and critically damped responses look like, and why derivative action hates noise.* (about 30 min)

### Braking before the wall

When you run towards a doorway, you do not wait until you are in it to slow down. You see that you are approaching fast and start braking early. Your decision depends not only on *how far* you are from the doorway, but on *how fast* that distance is shrinking.

A proportional controller only looks at how far. It pushes hard while the error is large and keeps pushing, a little less, all the way to the set point. If the thing it moves has inertia, like a robot arm, a cart or a drone, the arm arrives with speed and sails past. The third term of PID, **derivative action**, adds the missing information: the rate of change.

### Systems that bounce

Some plants respond smoothly to a push, like a heater warming a room. Others carry momentum and can bounce, like a mass on a spring. A robot joint with a flexible gearbox, a car's suspension and a camera gimbal all behave a bit like a mass on a spring.

Engineers describe a spring-like system with two numbers: how fast it naturally wants to oscillate, and how strongly it resists oscillating. The second is the **damping ratio**, written ζ (zeta). It sorts step responses into three families:

- **Underdamped (ζ < 1):** the output rises quickly, overshoots and rings before settling. The smaller ζ, the bigger and longer the ringing.
- **Critically damped (ζ = 1):** the fastest possible response that never overshoots.
- **Overdamped (ζ > 1):** no overshoot, but sluggish; the output creeps up to its final value.

For an underdamped system of this standard type, the overshoot depends only on ζ:

```
overshoot = exp(−π · ζ / √(1 − ζ²))
```

Working it through: ζ = 0.2 gives about 53 % overshoot, ζ = 0.4 about 25 %, ζ = 0.6 about 9.5 %, and ζ = 0.7 about 4.6 %. A door closer on a heavy door is tuned near critical damping: it shuts firmly but does not bounce.

### What derivative action does

The derivative term multiplies the rate of change by a gain **Kd**:

```
action = Kp · error + Ki · (sum of error) + Kd · (rate of change of error)
```

Suppose the set point is fixed and the arm is moving towards it. The error is shrinking, so its rate of change is negative, and the derivative term pushes *against* the motion. The faster the arm approaches, the harder it brakes. When the arm is still, the derivative term is zero and does nothing. Its whole job is to resist motion, which is exactly what physical damping does. In effect, **derivative action adds damping**.

You can see this in the maths for a mass-spring plant. For the explorer's second-order plant with time constant τ = 1 s, damping ζ = 0.4 and gain K = 1, under proportional plus derivative control, the closed loop is again a mass-spring system with

```
natural frequency   ωn = √(1 + Kp)
damping ratio       ζ_closed = (0.8 + Kd) / (2 · √(1 + Kp))
```

With Kp = 2 and no derivative, ζ_closed = 0.8 / 3.46 ≈ 0.23, which predicts about 47 % overshoot: much bouncier than the plant on its own, because the proportional gain stiffens the "spring" without adding any damping. Add Kd = 1 and ζ_closed rises to 1.8 / 3.46 ≈ 0.52, predicting about 15 %. Critical damping needs 0.8 + Kd = 3.46, so Kd ≈ 2.66.

### Checking it in the explorer

Choose the **2nd order** plant with τ = 1 s and ζ = 0.4. Select **PID** and set Ki = 0, so only the P and D terms act, and Kp = 2. Then step Kd up. The explorer reports approximately:

```
Kd = 0     overshoot 46 %    settling 8.4 s
Kd = 0.5   overshoot 28 %    settling 5.9 s
Kd = 1.0   overshoot 14 %    settling 3.2 s
Kd = 2.0   overshoot 0.5 %   settling 2.3 s
Kd = 2.66  overshoot 0 %     settling 3.6 s
Kd = 3.0   overshoot 0 %     settling 4.2 s
```

These agree with the formula to within a percent or two; the small differences come from the explorer's digital sampling and its filtered derivative. Notice something surprising: the fastest settling is *not* at critical damping. A touch of underdamping, here ζ ≈ 0.8 at Kd = 2, lets the output rise faster and only just kiss the 2 % band. Past critical damping the response gets steadily more sluggish. Derivative action, like the other terms, can be overdone.

Notice also that the steady-state error stays at 0.333 throughout. Derivative action acts only on change, so it cannot fix a steady error. That is still the integral term's job.

> **Interactive:** Choose the 2nd-order plant (τ = 1 s, ζ = 0.4), select PID and set Ki = 0 and Kp = 2. Raise Kd from 0 to 3 and watch overshoot fall. Then add sensor noise of 0.01 and watch the control effort become jagged as Kd grows. Try it at https://tactiverge.win/academy/lab/#feedback

### The catch: derivative action amplifies noise

A rate of change is a difference divided by a time step. Real sensors are noisy, and dividing a small random wobble by a small time step makes a large number.

A worked example. A position sensor reads with random noise of about ±0.01 (standard deviation 0.01), and the controller updates every 0.01 s. Even if the arm is perfectly still, two successive readings differ by a random amount with standard deviation √2 × 0.01 ≈ 0.014. Dividing by 0.01 s gives a fake velocity of about 1.4 units per second, in a random direction, every update. With Kd = 1, that is 1.4 units of random action. Compare the proportional term: Kp = 2 times noise of 0.01 is only 0.02. The derivative term has made the noise seventy times worse.

The actuator then receives a jagged command. A motor driven this way buzzes, heats up and wears its gears, even if the arm's average position looks fine.

Engineers use two standard defences:

1. **Filter the derivative.** Smooth the rate estimate with a low-pass filter, so that quick random jumps are averaged out while genuine motion still comes through. The explorer does this with a 0.05 s filter. In a simulation of the noisy case above, the filter cuts the random part of the actuator command from about 1.5 to about 0.2. The price is a little delay in the derivative's reaction.
2. **Take the derivative of the measurement, not the error.** If the set point jumps suddenly, the error jumps too, and its "rate of change" for that one instant is enormous. A controller that differentiates the error gives the actuator a violent kick at every set point change. Differentiating the measured output instead gives the same braking during normal motion, because when the set point is fixed the two rates are equal and opposite, but no kick. The explorer uses this form.

### When to use derivative action

Derivative action is most useful on plants with inertia and little natural damping: robot joints, quadcopter attitude, positioning stages. It is often left out on slow, smooth plants such as temperature control, where there is little to brake and the noise cost outweighs the benefit. Many industrial loops run as PI only.

### Recap

- Derivative action reacts to the rate of change, so it brakes before the set point is reached and resists motion: it adds damping.
- The damping ratio ζ classifies responses: underdamped (ζ < 1) overshoots and rings, critically damped (ζ = 1) is the fastest without overshoot, overdamped (ζ > 1) is sluggish.
- Proportional gain stiffens the loop and lowers its effective damping; derivative gain raises it back.
- Derivative action cannot remove steady-state error.
- It amplifies sensor noise, so real controllers filter it and usually differentiate the measurement rather than the error.

> **Feel it with your hand.** Hold a pen upright on your palm and try to keep it balanced. You do not just react to how far it has tilted; you react to how fast it is falling. That is derivative action. Now try it with your eyes half closed, so your view is "noisy". Your corrections become jerky, which is the noise problem in miniature.

#### Check your understanding

1. A step response rises, overshoots by 30 % and rings a few times before settling. How would you describe it?
   A) Overdamped
   B) Critically damped
   C) Underdamped
   D) Unstable

2. The set point is fixed and a joint is moving quickly towards it. What does the derivative term do?
   A) Pushes against the motion, braking the joint before it arrives
   B) Pushes harder in the direction of motion to arrive sooner
   C) Nothing, because the error is not zero
   D) Removes the steady-state error

3. A sensor has noise with standard deviation 0.02 and the controller samples every 0.01 s. Roughly how large is the noise in a raw, unfiltered rate estimate?
   A) About 0.02 per second
   B) About 2.8 per second
   C) About 0.0002 per second
   D) About 200 per second

4. Why do many controllers take the derivative of the measured output rather than of the error?
   A) It makes the controller open-loop
   B) It removes sensor noise completely
   C) It is the only way to get zero steady-state error
   D) It avoids a violent kick to the actuator whenever the set point jumps

5. On a lightly damped plant under P control with steady-state error 0.333, you add derivative action. What happens to the steady-state error?
   A) It falls to zero
   B) It stays the same, because derivative action only responds to change
   C) It doubles
   D) It becomes negative

**Go further:**

- Wikipedia — Damping: https://en.wikipedia.org/wiki/Damping — Covers the damping ratio and the underdamped, critically damped and overdamped cases, with diagrams of each response.


## 5.5 Tuning a PID controller systematically

*How to measure a step response, a step-by-step manual tuning procedure for P, D and I, and how to keep a tuning log that someone else could repeat.* (about 35 min)

### From knobs to a method

You now know what each PID term does. Tuning means choosing the three gains for a particular machine. It is tempting to twiddle all three until the response "looks OK", but that wastes time, gives results you cannot explain, and usually produces a controller that works only on the day you tuned it.

A systematic approach has three parts: decide what "good" means *before* you start, change one thing at a time, and write everything down. This lesson walks through each, ending with a complete worked tuning session on the explorer's second-order plant.

### Measuring a step response

The standard test is a **step**: change the set point suddenly, say from 0 to 1, and record what the output does. Four numbers summarise the result:

- **Rise time:** how long the output takes to climb from 10 % to 90 % of its final value. It measures speed.
- **Overshoot:** how far the peak goes above the final value, as a percentage of the final value. A peak of 1.10 on a final value of 1.00 is 10 % overshoot.
- **Settling time:** the time after which the output stays within a band around its final value, commonly ±2 %. It captures both speed and ringing.
- **Steady-state error:** the set point minus the final value.

These are the metrics the explorer reports. They pull against each other: a faster rise usually costs more overshoot, and removing steady-state error with integral action usually adds some.

### Write the requirement first

Before touching a gain, write down what you need, with numbers. For a joint that moves a camera, it might be:

```
overshoot          < 10 %
settling time (2%) < 3 s
steady-state error ≈ 0
```

Now "good" is something you can check, not a matter of taste. You also know when to stop: once all three are met with some margin, further tweaking is risk without reward.

### A manual tuning procedure

There are many tuning methods. This one is simple, safe and works on most plants a student will meet. It adds the terms in the order P, then D, then I.

1. **Start safe.** Set Ki = 0 and Kd = 0, and a small Kp. On real hardware, make sure the machine can move without hitting anything and that someone can cut the power.
2. **Raise Kp** until the response is reasonably fast and begins to overshoot noticeably. Do not chase zero error yet; P alone cannot reach it.
3. **Add Kd** to damp the overshoot. Raise it until the overshoot is small. If the response becomes sluggish or the actuator command becomes jagged with noise, back off.
4. **Add Ki** slowly to remove the steady-state error. Start small and increase until the error disappears in an acceptable time. Expect overshoot to return; stop before it breaks your requirement.
5. **Retune lightly.** Small adjustments to all three, one at a time, to meet every requirement with margin.
6. **Test beyond the tuning case.** Try a disturbance, a different step size, and noise. A controller that only works for one step is not finished.

Change **one** gain at a time, and change it by a clear amount, such as doubling or halving, so that each run teaches you something.

### Worked example: a tuning log

Here is a complete session on the explorer's **2nd-order** plant (τ = 1 s, ζ = 0.4), aiming for the requirement above. Every row is a single change from the row before it, and the numbers are what the explorer reports.

```
run  Kp  Ki   Kd   rise    overshoot  settling  ss error  note
1    2   0    0    0.72 s  46 %       8.4 s     0.33      too bouncy, big error
2    5   0    0    0.47 s  62 %       none      0.17      faster, worse ringing
3    5   0    1    0.56 s  29 %       4.2 s     0.17      D is damping it
4    5   0    2    0.70 s  9.5 %      2.3 s     0.17      nearly there
5    5   0    3    0.97 s  0.5 %      1.6 s     0.17      well damped; now fix error
6    5   3    3    0.86 s  14 %       4.8 s     0.00      error gone, too much I
7    5   1    3    1.21 s  0 %        4.3 s     0.01      slow creep to set point
8    5   1.5  3    1.09 s  1.1 %      1.7 s     0.00      meets all three
```

The log tells a story anyone can follow. Raising Kp in run 2 made things faster but worse; derivative in runs 3 to 5 tamed the ringing; integral in run 6 overshot the requirement, run 7 undershot it, and run 8 split the difference. Notice that run 7 has *no* overshoot but a long settling time: the output creeps up to the set point, which is the slow-integral problem from the integral lesson.

### Checking with code

You can reproduce the trend with a short simulation. This one uses a simpler method than the explorer and the exact velocity rather than a filtered estimate, so its numbers differ slightly, but the pattern is the same:

```python
def step_response(kp, ki, kd, zeta=0.4, dt=0.001, t_end=10.0):
    """PID (derivative on measurement) driving tau^2*y'' + 2*zeta*tau*y' + y = u, tau = 1 s."""
    y, v, integral, out = 0.0, 0.0, 0.0, []
    for _ in range(int(t_end / dt)):
        error = 1.0 - y
        integral += error * dt
        u = kp * error + ki * integral - kd * v
        v += dt * (u - y - 2 * zeta * v)
        y += dt * v
        out.append(y)
    return out

def metrics(ys, dt=0.001):
    final = ys[-1]
    overshoot = max(0.0, (max(ys) - final) / final * 100)
    outside = [i for i, y in enumerate(ys) if abs(y - final) > 0.02 * abs(final)]
    settle = (outside[-1] + 1) * dt if outside else 0.0
    return overshoot, settle, round(1.0 - final, 3) + 0.0

for gains in [(2, 0, 0), (5, 0, 3), (5, 3, 3), (5, 1.5, 3)]:
    os_pct, ts, err = metrics(step_response(*gains))
    print(f"Kp, Ki, Kd = {gains}: overshoot {os_pct:5.1f} %, "
          f"settling {ts:4.2f} s, error {err:6.3f}")
```

Output:

```
Kp, Ki, Kd = (2, 0, 0): overshoot  45.8 %, settling 8.38 s, error  0.326
Kp, Ki, Kd = (5, 0, 3): overshoot   2.1 %, settling 2.16 s, error  0.167
Kp, Ki, Kd = (5, 3, 3): overshoot  16.0 %, settling 4.48 s, error  0.000
Kp, Ki, Kd = (5, 1.5, 3): overshoot   2.5 %, settling 2.69 s, error -0.001
```

The two models disagree by a few percent, and the final gains still meet the requirement in both. That is a useful lesson in itself: if a controller only works in one exact model, it will probably not work on the real machine, which differs from every model.

> **Interactive:** Choose the 2nd-order plant (τ = 1 s, ζ = 0.4) and PID. Replay the tuning log one row at a time, then try to beat run 8: can you get settling under 1.5 s with overshoot under 10 %? Turn on the load disturbance to test your final gains. Try it at https://tactiverge.win/academy/lab/#feedback

### Rules of thumb and formal methods

Your tuning log shows the usual effects of raising each gain:

- **Raising Kp:** faster rise, more overshoot, smaller (but not zero) steady error.
- **Raising Ki:** removes steady error, faster rise, more overshoot, longer settling if overdone.
- **Raising Kd:** less overshoot and ringing, slower rise if overdone, more noise in the actuator command.

These are tendencies, not laws; on some plants an effect can reverse. Use them to guess the next experiment, then let the measurement decide.

There are also formal recipes. The best known is the **Ziegler–Nichols** method from the 1940s: raise Kp alone until the loop oscillates steadily, note that gain Ku and the oscillation period Tu, then compute starting gains from them (for the classic PID rule, Kp = 0.6 · Ku, with the integral time Tu / 2 and the derivative time Tu / 8). It is quick, but it deliberately drives the system to the edge of instability, which can be unsafe on real hardware, and its results are usually aggressive, with noticeable overshoot. Treat its gains as a starting point to refine, not a finished answer. Engineers with a good model of the plant often tune in simulation first and then confirm on hardware.

### Recap

- Define "good" with numbers before tuning: limits on overshoot, settling time and steady error.
- Measure step responses with rise time, overshoot, settling time and steady-state error.
- Tune P first, then D to damp, then I to remove steady error, changing one gain at a time.
- Keep a log of every run: gains, metrics and a note. It turns tuning into evidence that someone else can check.
- Test the final gains under disturbances and noise, not just the step you tuned on.

> **Keep the failed runs.** A tuning log is a record of an experiment. Keep every run, including the bad ones, and do not overwrite a row when you change your mind. If you report a controller's performance, say which conditions it was tested under and include the runs where it struggled. Someone repeating your work needs to know where its limits are.

#### Project: Simulation project: tune to a specification

Use the feedback explorer or the Python listing in this lesson.

1. Choose the **2nd-order** plant and set ζ = 0.2, a much bouncier plant than the worked example.
2. Write a requirement: overshoot under 10 %, settling time under 4 s, steady-state error below 0.01.
3. Follow the manual procedure (P, then D, then I), changing one gain per run. Record every run in a log with the same columns as the worked example.
4. When you meet the requirement, test your gains with the load disturbance on and with sensor noise of 0.01. Note any problems.
5. Write a short paragraph summarising what you learned about this plant compared with the ζ = 0.4 example.

No hardware is needed for this project.

**Deliverables**

- A written requirement with three numerical limits
- A tuning log with at least six runs, one change per run
- Results of disturbance and noise tests on the final gains
- A one-paragraph summary comparing the two plants

#### Check your understanding

1. A step response settles at 2.00 and peaks at 2.30. What is the overshoot?
   A) 30 %
   B) 0.30 %
   C) 13 %
   D) 15 %

2. Why should you change only one gain between tuning runs?
   A) So that any change in the response can be attributed to that one gain
   B) Because controllers can only store one gain at a time
   C) Because changing two gains always causes instability
   D) To make the tuning take longer

3. After adding derivative action, a response has 0.5 % overshoot but a steady-state error of 0.17. What is the usual next step?
   A) Raise Kd further
   B) Add a small amount of integral gain and increase it gradually
   C) Set Kp to zero
   D) Accept the error, because it cannot be removed

4. Which statement about the Ziegler–Nichols method is most accurate?
   A) It always gives the best possible gains
   B) It works without ever making the system oscillate
   C) It gives quick starting gains, but drives the loop to the edge of instability and the results usually need refining
   D) It only applies to integral gain

5. In the worked log, run 7 (Ki = 1) had no overshoot but a longer settling time than run 8 (Ki = 1.5). Why?
   A) The derivative gain was too high in run 7
   B) With too little integral gain, the output creeps slowly towards the set point and takes a long time to enter the 2 % band
   C) Run 7 was unstable
   D) Settling time is unrelated to the gains

**Go further:**

- Wikipedia — Ziegler–Nichols method: https://en.wikipedia.org/wiki/Ziegler%E2%80%93Nichols_method — The classic tuning recipe, with its table of starting gains for P, PI and PID controllers.


## 5.6 Practical control: saturation, windup, noise and delay

*The four problems that separate a controller that works in a simulation from one that works on a real robot, and the standard fixes for each.* (about 35 min)

### When the maths meets the machine

The PID equation assumes a perfect world: the actuator can deliver any command, the sensor reports the truth instantly, and the controller runs continuously. Real robots break all three assumptions. Motors have a maximum torque, sensors are noisy, and a microcontroller reads its sensors and updates its outputs at discrete moments, a little late each time.

None of these problems is exotic. Almost every real control loop runs into at least one of them, and many controllers that are tuned beautifully in simulation misbehave on their first day on hardware for exactly these reasons. This lesson covers four issues: actuator saturation, integrator windup, sensor noise, and sample rate with delay.

### 1. Actuator saturation

Every actuator has limits. A motor driver can only supply so much voltage, a heater has a maximum power, and a servo cannot turn faster than its top speed. When the controller asks for more than the limit, the actuator delivers the limit and no more. This is called **saturation**.

Saturation is not a failure; it is normal, especially just after a large set point change, when the error is big. Its first effect is simple: the response is slower than the linear maths predicts, because the controller cannot push as hard as it wants. On the explorer's first-order plant with PI gains Kp = 5 and Ki = 10, the unlimited controller briefly asks for an action of 5. If the actuator is limited to ±1.5, the 10–90 % rise takes about three times longer, roughly 0.9 s instead of 0.3 s.

The fix for slowness is a stronger actuator, or accepting a gentler response. The sneakier problem is what saturation does to the integral term.

### 2. Integrator windup

While the actuator is pinned at its limit, the error stays large, and the integrator keeps adding it up. The running total grows far beyond what the plant will need at rest, because none of the extra push is being delivered. When the output finally reaches the set point, that bloated total keeps the actuator pinned, and the output sails past. It then takes a long time for negative error to unwind the total. This is **integrator windup**.

The numbers on the explorer's first-order plant (Kp = 5, Ki = 10, set point 1) make the point:

```
actuator              overshoot   settling (2%)
unlimited             about 7 %   about 1.5 s
limited ±1.5          about 31 %  about 3.3 s
limited + anti-windup about 0 %   about 1.5 s
```

Limiting the actuator more than quadrupled the overshoot, not because the actuator is weak, but because the integrator was storing push it could never deliver.

**Anti-windup** schemes stop that from happening. The simplest, which the explorer uses, is **conditional integration**: while the actuator is saturated *and* the error is pushing further into the limit, stop adding to the integral. Other common schemes clamp the integral total to a maximum, or feed back the difference between the requested and delivered command to bleed the integral down. Here is conditional integration in a short simulation, using simple Euler steps:

```python
def simulate(anti_windup, kp=5.0, ki=10.0, u_max=1.5, dt=0.01, t_end=10.0):
    y, integral, peak = 0.0, 0.0, 0.0
    for _ in range(int(t_end / dt)):
        error = 1.0 - y
        u_wanted = kp * error + ki * integral
        u = max(-u_max, min(u_max, u_wanted))     # the actuator's limit
        pinned = u != u_wanted and (u_wanted > 0) == (error > 0)
        if not (anti_windup and pinned):
            integral += error * dt
        y += dt * (-y + u)                        # first-order plant, K = 1, tau = 1 s
        peak = max(peak, y)
    return peak

print(f"peak without anti-windup: {simulate(False):.3f}")
print(f"peak with anti-windup:    {simulate(True):.3f}")
```

Output:

```
peak without anti-windup: 1.305
peak with anti-windup:    1.000
```

Windup also happens when the robot is blocked. If a gripper closes on an object and the controller still wants it to close further, the integrator winds up against the obstacle. When the object is removed, the gripper snaps shut. That is a safety issue as well as a performance one, and a good reason to always include anti-windup.

> **Interactive:** On the 1st-order plant, choose PI with Kp = 5 and Ki = 10. Turn on actuator saturation with a limit of 1.5, then switch anti-windup off and on and compare the overshoot. Finally add sensor noise and see how it affects the control effort. Try it at https://tactiverge.win/academy/lab/#feedback

### 3. Sensor noise

Every measurement includes some noise. The controller cannot tell noise from real error, so it reacts to both. Each term reacts differently:

- The **proportional** term passes noise straight through, scaled by Kp. High proportional gains make the actuator jitter.
- The **integral** term averages noise out, because random positive and negative errors largely cancel in the sum. It is the least sensitive.
- The **derivative** term amplifies noise badly, as the derivative lesson showed, because it divides small random differences by a small time step.

The standard responses are to improve the sensor or its mounting first, then filter: smooth the measurement or the derivative with a low-pass filter. Every filter adds delay, though, and delay is the next problem. Noise is a trade-off, not something you can filter away for free.

### 4. Sample rate and delay

A digital controller runs in a loop: read the sensor, compute, write the actuator, wait, repeat. Between updates it is blind, and the reading it acts on is already a little old. Delays also come from filtering, communication between boards, and the actuator's own response.

Delay is dangerous because the controller is correcting for where the system *was*, not where it *is*. Return to the toy model from the proportional lesson, and make the controller see a reading one step old:

```python
def run(kp, delay, steps=8):
    pos = [0.0]
    for k in range(steps):
        seen = pos[max(0, k - delay)]      # the controller sees an old reading
        pos.append(pos[k] + kp * (100 - seen))
    return pos

for kp in (0.5, 1.0):
    for delay in (0, 1):
        print(f"Kp={kp} delay={delay}:", " ".join(f"{p:6.1f}" for p in run(kp, delay)))
```

Output:

```
Kp=0.5 delay=0:    0.0   50.0   75.0   87.5   93.8   96.9   98.4   99.2   99.6
Kp=0.5 delay=1:    0.0   50.0  100.0  125.0  125.0  112.5  100.0   93.8   93.8
Kp=1.0 delay=0:    0.0  100.0  100.0  100.0  100.0  100.0  100.0  100.0  100.0
Kp=1.0 delay=1:    0.0  100.0  200.0  200.0  100.0    0.0    0.0  100.0  200.0
```

Without delay, Kp = 0.5 creeps smoothly to 100 and Kp = 1 gets there in one step. With just one step of delay, Kp = 0.5 overshoots by 25 %, and the "perfect" Kp = 1 oscillates between 0 and 200 forever. In this model, one step of delay halves the gain at which the loop becomes unstable, from 2 down to 1. That is the general pattern: **delay lowers the gain you can safely use**, so it limits how fast a loop can be.

Practical consequences:

- **Sample fast enough.** A common rule of thumb is to sample at least ten times faster than the quickest response you want the loop to control. A joint that should settle in 0.1 s needs a loop much faster than 10 times per second.
- **Sample at a steady rate.** The integral and derivative calculations assume a known time step. A loop whose timing jitters because other code sometimes runs long will behave unpredictably. Measure the actual time step, or better, run the control loop on a timer.
- **Reduce delay everywhere.** Avoid heavy filtering, slow communication and long computations inside the loop. Each adds lag.
- **Retune for the real loop rate.** Gains found at one sample rate may not transfer to another.

### Putting it together

A practical PID controller on a real robot usually includes all of these fixes: output limits matching the actuator, anti-windup on the integral, a filtered derivative of the measurement, and a fixed, fast loop rate. It is still the same three-term idea; the extra parts make it survive contact with the real world.

### Recap

- **Saturation:** actuators have limits; responses are slower than the linear maths predicts.
- **Windup:** a saturated or blocked actuator lets the integral grow uselessly, causing large overshoot. Conditional integration or clamping prevents it.
- **Noise:** P passes it, D amplifies it, I averages it; filter carefully, because filters add delay.
- **Delay and sample rate:** the controller acts on old information, which lowers the safe gain. Sample fast, at a steady rate, and keep delays short.

> **Real actuators can hurt people.** Saturation and windup are not just about neat graphs. A wound-up integrator can make a motor lunge at full power the moment an obstruction is cleared, and a loop made unstable by delay can shake a mechanism hard. If you ever test a controller on real hardware, do it only with adult supervision, at low voltage, with small and slow mechanisms, with fingers and hair well clear of moving parts, and with a way to cut the power instantly. Test new gains in simulation first.

#### Check your understanding

1. A PI controller's actuator is limited to ±1.5. After a large step the output overshoots far more than it did with an unlimited actuator. What is the most likely cause?
   A) Sensor noise
   B) The derivative gain is too high
   C) Integrator windup: the integral kept growing while the actuator was pinned at its limit
   D) The sample rate is too fast

2. What does conditional integration do?
   A) Stops adding to the integral while the actuator is saturated and the error pushes further into the limit
   B) Doubles the integral gain when the error is large
   C) Removes the proportional term during saturation
   D) Filters noise out of the derivative term

3. Which PID term is least sensitive to random sensor noise?
   A) Proportional
   B) Derivative
   C) All are equally sensitive
   D) Integral

4. In the toy model, adding one step of measurement delay made Kp = 1 oscillate forever. What general lesson does this illustrate?
   A) Delay has no effect on stability
   B) Delay lowers the gain at which a loop becomes unstable, so it limits how fast the loop can safely respond
   C) Delay only matters for integral action
   D) Delay can be removed by raising the gain

5. A robot joint should settle in about 0.2 s. Which loop rate is the most sensible starting choice?
   A) 1 update per second
   B) 5 updates per second
   C) About 100 updates per second or more, at a steady rate
   D) Whatever rate the code happens to run at

**Go further:**

- Wikipedia — Integral windup: https://en.wikipedia.org/wiki/Integral_windup — A short article on why windup happens and the common ways to prevent it.
