# Embedded Systems

*Tactiverge Academy course pack · version 1.0.0*

The small computers hidden inside machines: digital logic, microcontrollers, the code that runs on them, and how they read sensors and talk to each other.

**Audience:** Curious students aged 13 and over. No prior electronics or programming experience needed; activities favour simulation over hardware.

> 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: Digital electronics fundamentals

Voltage, current and resistance, and how electronic circuits represent information as ones and zeros using logic gates.

**Objectives**

- Explain voltage, current and resistance and apply Ohm's law to simple circuits.
- Represent numbers in binary and hexadecimal and convert between them.
- Describe the behaviour of AND, OR, NOT and XOR gates using truth tables.
- Explain how logic levels map physical voltages to digital values.


## 1.1 Voltage, current and resistance

*The three quantities behind every circuit, how Ohm's law ties them together, and where the popular water analogy helps and where it misleads.* (about 25 min)

### Why start here

Every embedded system, from a microcontroller blinking an LED to the electronics in a robot arm, is a set of circuits. Before you can choose a resistor, read a sensor or work out whether a pin can drive a motor, you need three ideas: **voltage**, **current** and **resistance**. They are also the ideas that keep you and your components safe. Most beginner mistakes that destroy parts come down to one of these three being misunderstood.

### Charge and current

Matter contains electric **charge**. In a metal wire, some electrons are free to drift from atom to atom. When they drift steadily in one direction, charge flows, and that flow is an electric **current**.

Current is measured in **amperes**, or amps (A). One amp means one **coulomb** of charge passing a point every second, and one coulomb is the charge of about 6.24 × 10¹⁸ electrons. Electronics usually deals in smaller currents: a small indicator LED might use 10 **milliamps** (mA), which is 0.010 A, and a microcontroller asleep might draw a few **microamps** (µA).

By convention, current is drawn flowing from the positive terminal of a supply, through the circuit, to the negative terminal. Electrons actually drift the other way, because they are negatively charged. This **conventional current** direction was fixed before electrons were discovered, and every circuit diagram still uses it. It never changes the arithmetic.

Current needs a complete loop, called a **circuit**. Break the loop anywhere, with a switch or a cut wire, and the current stops everywhere in that loop at once.

### Voltage

Charge does not flow on its own. Something has to push it. **Voltage** measures how much energy each unit of charge gains or loses between two points. One **volt** (V) means one joule of energy per coulomb.

The key phrase is *between two points*. Voltage is always a difference. When someone says "this pin is at 3.3 V", they mean 3.3 V relative to a reference point called **ground**, usually the negative terminal of the supply. A bird on a single power line is not hurt, because both its feet are at nearly the same voltage, so there is almost no difference across its body to drive a current.

A battery or a power supply creates a voltage difference. Charge flowing round the circuit gains energy in the supply and gives it up in the components: as light in an LED, heat in a resistor, motion in a motor.

### Resistance and Ohm's law

Different materials let current through more or less easily. **Resistance**, measured in **ohms** (Ω), describes how strongly something opposes current. Copper wire has very little; a **resistor** is a component made to have a specific resistance, such as 220 Ω or 10 kΩ (10,000 Ω).

For many materials, including ordinary resistors, current is proportional to voltage. Double the voltage across a resistor and the current doubles. This is **Ohm's law**:

```
V = I × R

V  voltage across the component, in volts
I  current through it, in amps
R  its resistance, in ohms
```

Rearranged, it gives whichever quantity you are missing: I = V / R and R = V / I.

### Worked examples

1. A 1 kΩ resistor is connected across a 5 V supply. The current is I = 5 / 1000 = 0.005 A, or **5 mA**.
2. A sensor needs 20 mA when 5 V is across it. Its effective resistance is R = 5 / 0.020 = **250 Ω**.
3. A 470 Ω resistor carries 6 mA. The voltage across it is V = 0.006 × 470 = **2.82 V**.

A useful habit: work in volts, milliamps and kilohms together. Because milli and kilo cancel, V = mA × kΩ. In example 3, 6 mA × 0.47 kΩ = 2.82 V, with no powers of ten to track.

### Measuring

A **multimeter** measures all three quantities, but in different ways:

- **Voltage** is measured *across* a component, with the two probes on either side of it, because voltage is a difference between two points.
- **Current** is measured *through* a component: the circuit must be broken and the meter inserted into the loop, so the current flows through the meter.
- **Resistance** is measured with the component unpowered, because the meter uses its own small current to measure it.

Connecting a meter set to current directly across a supply is a classic mistake. The current setting has almost no resistance, so it acts like a short circuit.

### The water analogy

Electricity is invisible, so teachers often compare a circuit to water in pipes:

- **Voltage** is like water **pressure**: the push that makes water flow.
- **Current** is like the **flow rate**: litres per second passing a point.
- **Resistance** is like a **narrow section of pipe**: the narrower it is, the less flow for the same pressure.
- A **battery** is like a **pump**, raising water to a higher pressure so it can flow round and back.

The analogy captures Ohm's law nicely. More pressure gives more flow; a narrower pipe gives less. It also explains why current is the same all the way round a single loop: water cannot pile up or vanish in a sealed pipe, so whatever flows into a section must flow out.

### Where the analogy breaks

Analogies are tools with limits. This one misleads in several ways:

1. **Wires are already full.** Pipes can be empty, but a wire is always full of free electrons. When you close a switch, the electrons near the lamp start moving almost immediately because the push travels through the whole wire very fast. The electrons themselves drift slowly, typically well under a millimetre per second.
2. **An open circuit does not leak.** An open water pipe sprays water. A disconnected wire does not spray electrons. With the loop broken, current simply stops.
3. **Not everything obeys Ohm's law.** An LED, a diode or a motor does not have a fixed resistance. An LED passes almost no current until the voltage across it reaches about its forward voltage, then current rises very steeply. Treating it as a fixed resistance gives wrong answers, which is why the next lesson calculates LED resistors carefully.
4. **Energy is the point, not the stuff.** What a circuit delivers is energy, carried by the field around the wires, not "electricity" being used up. The same current flows into and out of a lamp; the energy is what changes.

Use the analogy to build intuition, then trust the definitions and Ohm's law when the two disagree.

### Recap

- **Current** (A) is the rate of flow of charge, and needs a complete loop.
- **Voltage** (V) is energy per unit charge, always measured between two points; ground is the usual reference.
- **Resistance** (Ω) opposes current. For a resistor, V = I × R.
- Measure voltage across a component, current through it, and resistance with the power off.
- The water analogy helps with Ohm's law, but wires are always full, open circuits do not leak, and many components are not simple resistors.

> **Low voltage only.** Everything in this module uses small batteries or the 3.3 V and 5 V supplies found on hobby boards. Never experiment with mains electricity (the wall sockets, at around 230 V or 120 V depending on your country), which can kill. Never open power adapters or devices that plug into the wall. Even small batteries can become dangerously hot if their terminals are shorted, so never connect a wire straight across a battery. Do hands-on activities only with adult supervision.

#### Project: Paper project: Ohm's law practice

Work these out on paper or with a calculator, then check them with a short Python program or a free online circuit simulator.

1. Find the current through 100 Ω, 330 Ω, 1 kΩ and 10 kΩ resistors, each connected across 5 V. Give answers in mA.
2. A device draws 0.15 A from a 9 V battery. What is its effective resistance?
3. Plot current against voltage for a 1 kΩ resistor from 0 V to 5 V in 1 V steps. What shape is the graph, and what does its slope represent?
4. In two or three sentences, explain one way the water analogy would mislead someone, using your own example.

This project needs no hardware.

**Deliverables**

- Four currents with working shown
- The effective resistance of the device
- A current–voltage graph with its slope explained
- A short explanation of one limit of the water analogy

**Safety (adult supervision required):** This project is paper and simulation only. If you later try any of it with real parts, do so only with adult supervision, using small batteries (no more than a few volts), never shorting a battery's terminals and never using mains electricity.

#### Check your understanding

1. A 2.2 kΩ resistor has 3.3 V across it. What current flows through it?
   A) 7.26 mA
   B) 1.5 mA
   C) 0.67 mA
   D) 15 mA

2. Why is voltage always described between two points?
   A) Because voltage is the energy difference per unit charge between two places in a circuit
   B) Because voltmeters have two wires for safety
   C) Because current flows in two directions
   D) Because voltage only exists in batteries

3. How should a multimeter be connected to measure the current through a resistor?
   A) Across the resistor, one probe on each side
   B) Across the battery terminals
   C) In the loop, so the current flows through the meter
   D) With the power switched off

4. Which statement shows a limit of the water-in-pipes analogy?
   A) More pressure gives more flow, like more voltage gives more current
   B) A narrow pipe resists flow, like a resistor
   C) The flow into a sealed section equals the flow out
   D) A broken wire does not spray electrons the way a broken pipe sprays water

5. An LED does not obey Ohm's law. What does that mean in practice?
   A) Its current is not proportional to the voltage across it, so you cannot treat it as a fixed resistance
   B) It has zero resistance
   C) It can only be used with alternating current
   D) It always draws exactly 20 mA

**Go further:**

- Wikipedia — Ohm's law: https://en.wikipedia.org/wiki/Ohm%27s_law — History, the formal statement and where the law does and does not apply.
- Falstad circuit simulator: https://www.falstad.com/circuit/ — A free circuit simulator that runs in a web browser, with animated current flow. Good for checking your answers safely.


## 1.2 Power, series and parallel circuits

*How much power a component dissipates, how resistors combine in series and parallel, how a voltage divider works, and how to calculate the resistor for an LED.* (about 30 min)

### Why this matters

A robot's electronics are many components connected together. To design them you need to answer three practical questions again and again. Will this part overheat? What voltage will appear at this point? What current will flow from the supply? This lesson gives you the tools: the power equations, the rules for series and parallel connections, and the voltage divider. It ends with the calculation every embedded engineer does early on: choosing the resistor for an LED.

### Power

**Power** is the rate at which energy is transferred, measured in **watts** (W). One watt is one joule per second. In a circuit, power is voltage times current:

```
P = V × I
```

This makes sense from the definitions: voltage is energy per coulomb, current is coulombs per second, so their product is energy per second.

Combining with Ohm's law (V = I × R) gives two more forms, useful for resistors:

```
P = I² × R
P = V² / R
```

In a resistor, all of that power becomes heat. Resistors are sold with a **power rating**; common small through-hole resistors are rated at 0.25 W. Exceed it and the resistor gets hot, drifts in value and can burn.

**Worked example.** A 100 Ω resistor sits across 5 V. The current is 5 / 100 = 50 mA, and the power is 5 × 0.05 = 0.25 W. That is exactly the rating of a 0.25 W resistor, with no margin at all. A careful designer would use a resistor rated at 0.5 W or more, or change the design. A good habit is to keep parts at no more than about half their rating.

### Series circuits

Components are in **series** when they sit one after another in a single path, so the same current must flow through all of them.

- **Current** is the same through every component.
- **Voltages add up.** The supply voltage is shared between the components: the voltages across them sum to the supply voltage. This is **Kirchhoff's voltage law**: around any closed loop, the rises and drops in voltage add to zero.
- **Resistances add.** R_total = R1 + R2 + R3 + …

**Example.** A 220 Ω and a 330 Ω resistor in series across 5 V. Total resistance 550 Ω, current 5 / 550 ≈ 9.09 mA. The voltage across the 220 Ω resistor is 0.00909 × 220 ≈ 2.0 V and across the 330 Ω about 3.0 V. Check: 2.0 + 3.0 = 5.0 V.

### Parallel circuits

Components are in **parallel** when they are connected across the same two points, giving the current several paths.

- **Voltage** is the same across every branch.
- **Currents add up.** The current from the supply splits between the branches and rejoins. This is **Kirchhoff's current law**: the current flowing into a junction equals the current flowing out.
- **Resistances combine as reciprocals:** 1 / R_total = 1 / R1 + 1 / R2 + …

For exactly two resistors there is a shortcut, "product over sum":

```
R_total = (R1 × R2) / (R1 + R2)
```

**Example.** The same 220 Ω and 330 Ω, now in parallel: (220 × 330) / (220 + 330) = 72,600 / 550 = 132 Ω. The parallel combination is *smaller* than either resistor, because adding a path always makes it easier for current to flow. Across 5 V, the 220 Ω branch carries 22.7 mA, the 330 Ω branch 15.2 mA, and the supply provides the total, 37.9 mA, which matches 5 / 132.

Two equal resistors in parallel give exactly half the resistance of one. The lights in a house are wired in parallel, so each gets the full voltage and switching one off does not affect the others.

### The voltage divider

Two resistors in series make one of the most useful circuits in electronics, the **voltage divider**. Connect R1 from the supply to a middle point, and R2 from the middle point to ground. The voltage at the middle point is

```
Vout = Vin × R2 / (R1 + R2)
```

The same current flows through both resistors, so the supply voltage is shared in proportion to their resistances.

**Example.** With Vin = 5 V, R1 = 10 kΩ and R2 = 20 kΩ, Vout = 5 × 20 / 30 ≈ 3.33 V. Dividers like this are used to bring a sensor's 5 V signal down to a level safe for a 3.3 V microcontroller input. Many sensors are dividers themselves: a light-dependent resistor or a thermistor in series with a fixed resistor turns a changing resistance into a changing voltage that a microcontroller can measure.

**The catch: loading.** The formula assumes nothing draws current from the middle point. If you connect a load, it sits in parallel with R2 and changes the answer. In the example, a 20 kΩ load in parallel with R2 makes 10 kΩ, and Vout drops to 5 × 10 / 20 = 2.5 V. A divider is fine for feeding a high-resistance input such as a microcontroller pin, but it is not a power supply: never use one to power a motor or another circuit.

### Calculating an LED resistor

An LED is not a resistor. Once it lights, the voltage across it stays roughly constant, close to its **forward voltage**, whatever the current. A typical red LED has a forward voltage of around 2 V; blue and white LEDs are nearer 3 V. Above that voltage the current rises very steeply, so connecting an LED straight to a supply can let through a destructive current. A resistor in series limits it.

The resistor takes whatever voltage the LED does not:

```
R = (Vsupply − Vforward) / I
```

**Example.** Red LED (Vf ≈ 2.0 V), 5 V supply, target 10 mA:

```
R = (5.0 − 2.0) / 0.010 = 300 Ω
```

300 Ω is not a value you can usually buy. Resistors come in standard series; the common **E12** series has twelve values per decade: 1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8 and 8.2, times a power of ten. Pick the next value *up*, so the current is a little below the target rather than above it: 330 Ω. The actual current is then 3.0 / 330 ≈ 9.1 mA. Check the resistor's power: 3.0 V × 9.1 mA ≈ 27 mW, far below 0.25 W.

This short program does the same calculation for a 5 V and a 3.3 V supply:

```python
E12 = [1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2]

def next_standard(r):
    """Smallest E12 resistor value that is at least r ohms."""
    decade = 1.0
    while True:
        for base in E12:
            if base * decade >= r:
                return base * decade
        decade *= 10

def led_resistor(supply_v, led_v, target_ma):
    exact = (supply_v - led_v) / (target_ma / 1000)
    chosen = next_standard(exact)
    current_ma = (supply_v - led_v) / chosen * 1000
    power_mw = (supply_v - led_v) * current_ma
    return exact, chosen, current_ma, power_mw

for supply in (5.0, 3.3):
    exact, chosen, i, p = led_resistor(supply, 2.0, 10)
    print(f"{supply} V: exact {exact:.0f} ohm, use {chosen:.0f} ohm, "
          f"current {i:.1f} mA, resistor power {p:.0f} mW")
```

Output:

```
5.0 V: exact 300 ohm, use 330 ohm, current 9.1 mA, resistor power 27 mW
3.3 V: exact 130 ohm, use 150 ohm, current 8.7 mA, resistor power 11 mW
```

Always check the LED's datasheet for its forward voltage and maximum current, and check the microcontroller's datasheet for how much current a pin may supply. Pin limits are often lower than an LED's maximum, and they are covered in the microcontrollers module.

### Recap

- Power P = V × I = I² × R = V² / R. Keep resistors well within their power rating.
- **Series:** same current, voltages add, resistances add.
- **Parallel:** same voltage, currents add, resistances combine as reciprocals; the total is less than the smallest branch.
- **Voltage divider:** Vout = Vin × R2 / (R1 + R2), valid only when the load draws little current.
- **LED resistor:** R = (Vsupply − Vforward) / I, rounded up to a standard value, then check the current and power.

#### Project: Design project: an LED indicator

Design, and optionally build, a single-LED indicator powered by two AA cells in series (about 3 V).

1. Look up or assume a forward voltage of 2.0 V for a red LED. Calculate the exact resistor for 5 mA, then choose the next E12 value up and recalculate the current and the resistor's power.
2. Fresh AA cells can read a little above 1.5 V each. Recalculate the current for a 3.2 V supply. Is your design still safe?
3. Draw the circuit diagram, marking the direction of conventional current.
4. Optional build, only with an adult: assemble the circuit on a solderless breadboard with your chosen resistor, and measure the voltage across the LED and across the resistor with a multimeter. Do they add up to the battery voltage?

You can also build the circuit in a free online simulator instead of with real parts.

**Deliverables**

- Resistor calculation with the chosen standard value, current and power
- The recalculation for a 3.2 V supply
- A labelled circuit diagram
- If built: measured voltages compared with your predictions

**Safety (adult supervision required):** Build only with adult supervision. Use only two AA cells (about 3 V); never use mains power or mains adapters. Always include the series resistor; never connect an LED, or a bare wire, directly across the battery, as shorted batteries can get hot. Disconnect the battery before changing the circuit, and do not look directly into a bright LED at close range.

#### Check your understanding

1. A 47 Ω resistor carries 0.1 A. How much power does it dissipate?
   A) 4.7 W
   B) 0.47 W
   C) 0.047 W
   D) 470 W

2. What is the combined resistance of a 1 kΩ and a 1 kΩ resistor in parallel?
   A) 2 kΩ
   B) 1 kΩ
   C) 0 Ω
   D) 500 Ω

3. A voltage divider has Vin = 9 V, R1 = 2 kΩ (top) and R2 = 1 kΩ (bottom). What is Vout with no load?
   A) 3 V
   B) 6 V
   C) 4.5 V
   D) 1 V

4. Which statement about components in series is correct?
   A) They all have the same voltage across them
   B) The total resistance is less than the smallest resistor
   C) The same current flows through all of them
   D) Removing one leaves the others working

5. For a 5 V supply and an LED with a 3.0 V forward voltage, which resistor gives about 10 mA?
   A) 500 Ω
   B) 330 Ω
   C) 200 Ω, rounded up to 220 Ω
   D) 50 Ω

**Go further:**

- Wikipedia — Voltage divider: https://en.wikipedia.org/wiki/Voltage_divider — Derivation of the divider formula, the effect of loading, and examples with resistors and sensors.


## 1.3 Binary, hexadecimal and digital signals

*How computers count with only two symbols, why engineers write numbers in hexadecimal, and how a physical voltage becomes a reliable 0 or 1.* (about 25 min)

### Two states are enough

A light switch is on or off. A microcontroller pin is high or low. A bit in memory is 1 or 0. Digital electronics builds everything, from adding numbers to running a robot's control loop, out of signals that have only two allowed states. This lesson covers how numbers are written with two symbols, a shorthand engineers use constantly, and the physical trick that makes digital circuits so reliable.

### Counting in binary

In ordinary **decimal** (base 10), each place is worth ten times the place to its right: ones, tens, hundreds. The number 347 means 3 × 100 + 4 × 10 + 7 × 1.

**Binary** (base 2) works the same way with only the digits 0 and 1, and each place is worth *twice* the place to its right:

```
place value:  128  64  32  16   8   4   2   1
binary:         1   1   0   0   1   0   1   0
```

To read it, add the place values where there is a 1: 128 + 64 + 8 + 2 = **202**. Each binary digit is a **bit**.

To convert decimal to binary, divide by 2 repeatedly and record the remainders, then read them from the last to the first. For 13:

```
13 ÷ 2 = 6 remainder 1
 6 ÷ 2 = 3 remainder 0
 3 ÷ 2 = 1 remainder 1
 1 ÷ 2 = 0 remainder 1
reading upwards: 1101
```

Check: 8 + 4 + 1 = 13. Alternatively, subtract the largest place value that fits, write a 1, and continue with what is left.

### Bits and bytes

A group of 8 bits is a **byte**. With n bits you can make 2ⁿ different patterns, so

- 1 bit: 2 values (0 to 1)
- 4 bits: 16 values (0 to 15)
- 8 bits: 256 values (0 to 255)
- 16 bits: 65,536 values (0 to 65,535)

This matters constantly in embedded work. An 8-bit sensor reading cannot exceed 255, and a 10-bit converter gives readings from 0 to 1023. If you add 1 to an 8-bit counter holding 255, it wraps round to 0, a behaviour you will meet again when you study integer overflow.

The rightmost bit, worth 1, is the **least significant bit** (LSB); the leftmost is the **most significant bit** (MSB).

### Hexadecimal: binary for humans

Long strings of bits are hard to read and easy to miscopy. **Hexadecimal** (base 16) is a compact shorthand. It needs sixteen digits, so after 0–9 it uses the letters A–F for ten to fifteen:

```
binary  hex   decimal      binary  hex   decimal
0000    0     0            1000    8     8
0001    1     1            1001    9     9
0010    2     2            1010    A     10
0011    3     3            1011    B     11
0100    4     4            1100    C     12
0101    5     5            1101    D     13
0110    6     6            1110    E     14
0111    7     7            1111    F     15
```

The beauty of hex is that **one hex digit is exactly four bits**, called a **nibble**. To convert binary to hex, split the bits into groups of four from the right and replace each group:

```
1100 1010
   C    A      →  0xCA
```

The prefix `0x` is how C, Python and most datasheets mark a hex number. So 0xCA = 12 × 16 + 10 = 202, the same number as before. A byte is always exactly two hex digits, from 0x00 to 0xFF (255). When a datasheet says a register should be set to 0x3F, you can see at a glance that it means 0011 1111: the lower six bits set.

Python converts between these for you:

```python
n = 202
print(bin(n), hex(n))                 # Python's built-in conversions
print(int("11001010", 2), int("CA", 16))
print(f"{n:08b}  {n:02X}")            # fixed-width binary and hex
```

Output:

```
0b11001010 0xca
202 202
11001010  CA
```

### From voltages to bits

A wire does not carry a "1". It carries a voltage. A **logic level** is the agreement about which voltages count as 0 and which count as 1. In a 3.3 V system, 0 V is the obvious **low** (0) and 3.3 V the obvious **high** (1). But real signals are never exact: wires pick up interference, outputs sag under load, and supplies ripple.

So digital standards use *ranges* rather than exact values. As an example, one common 3.3 V standard specifies:

```
an input reads LOW  if it is below 0.8 V
an input reads HIGH if it is above 2.0 V
between 0.8 V and 2.0 V the result is not guaranteed

an output driving LOW  stays below 0.4 V
an output driving HIGH stays above 2.4 V
```

Always check the datasheet for the parts you actually use; thresholds differ between families and supply voltages.

Look at the gaps. A guaranteed high output is at least 2.4 V, but an input only needs 2.0 V to read high. That 0.4 V gap is the **noise margin**: a high signal can be disturbed by up to 0.4 V of noise and still be read correctly. The same 0.4 V margin exists at the low end, between 0.4 V and 0.8 V.

The forbidden zone in the middle matters too. A signal that sits there, perhaps because a pin is connected to nothing at all, can be read as 0 one moment and 1 the next. That is why unconnected inputs need **pull-up** or **pull-down** resistors, a topic for the microcontrollers module.

### Why digital is robust

Consider sending a measurement as an analogue voltage, where 1.37 V means 1.37 units. Any noise added on the way changes the value, and it cannot be removed afterwards, because the receiver cannot tell what the true value was. Copy the signal ten times through ten noisy stages and the errors pile up.

Now send the same information as bits. Each stage only has to decide "high or low". As long as the noise is smaller than the noise margin, every bit is read correctly, and each logic gate outputs a fresh, clean high or low. The signal is **regenerated** at every stage, so the noise does not accumulate. That is why a digital file can be copied a million times without change, and why a robot's sensor data can travel through cables and chips without degrading.

The price is resolution. A number stored in 8 bits can only take 256 values, so a continuous quantity must be rounded, and fast signals need many bits per second. Engineers choose the number of bits to suit the job.

### Recap

- Binary uses place values 1, 2, 4, 8, …; convert by adding place values or by repeated division by 2.
- n bits give 2ⁿ values; a byte (8 bits) holds 0–255.
- One hex digit is exactly four bits, so a byte is two hex digits, written with a 0x prefix.
- Logic levels are voltage ranges, with a forbidden zone in between; noise margins let signals survive interference.
- Digital signals are regenerated at each stage, so noise does not build up, at the cost of finite resolution.

#### Project: Paper and Python project: a conversion toolkit

1. By hand, convert 37, 100 and 255 to binary and to hex. Then convert 0x7F, 0xA5 and 0b10110011 to decimal.
2. Check every answer with Python's `bin()`, `hex()` and `int(text, base)`.
3. Write a Python function `to_binary(n)` that uses repeated division by 2 (without calling `bin()`) and returns the binary digits as a string. Test it against `bin()` for every number from 0 to 255.
4. Using the example 3.3 V thresholds in this lesson, decide whether each of these input voltages reads as 0, 1 or not guaranteed: 0.3 V, 1.4 V, 2.1 V, 3.0 V.

No hardware is needed for this project.

**Deliverables**

- Hand conversions with working, checked by Python
- A working to_binary function and its test loop
- Classified input voltages with reasons

#### Check your understanding

1. What is the binary number 10110 in decimal?
   A) 22
   B) 11
   C) 26
   D) 10110

2. What is 0x4E in binary?
   A) 0100 1101
   B) 0100 1110
   C) 0010 1110
   D) 1110 0100

3. How many different values can a 12-bit number represent?
   A) 12
   B) 144
   C) 2048
   D) 4096

4. Using the lesson's example thresholds, an input reads high above 2.0 V and a guaranteed high output is above 2.4 V. What is the high-level noise margin?
   A) 2.0 V
   B) 0.4 V
   C) 2.4 V
   D) 3.3 V

5. Why can a digital signal pass through many stages without the noise building up?
   A) Digital wires are immune to interference
   B) Digital signals use higher voltages
   C) Each stage only decides high or low and outputs a fresh, clean level, so noise smaller than the margin is removed
   D) Digital signals carry more information per wire than analogue ones

**Go further:**

- Wikipedia — Hexadecimal: https://en.wikipedia.org/wiki/Hexadecimal — The base-16 system, conversion methods and how hex is written in different programming languages.
- Wikipedia — Logic level: https://en.wikipedia.org/wiki/Logic_level — How different logic families map voltages to 0 and 1.


## 1.4 Logic gates and Boolean algebra

*The basic gates that make decisions from bits, truth tables that describe them completely, and the algebra that lets you simplify logic before you build it.* (about 30 min)

### Decisions made of bits

A robot's motor should run only if the start button has been pressed, the safety guard is closed and the emergency stop is not pressed. That sentence is a piece of logic, and it can be built directly in hardware from a few **logic gates**, or written as a line of code. Either way, the same rules apply. This lesson introduces the gates, the **truth tables** that describe them, and **Boolean algebra**, the arithmetic of true and false named after the mathematician George Boole.

In this lesson 1 means true (or high) and 0 means false (or low).

### The basic gates

A gate takes one or more input bits and produces one output bit. Each is completely described by a truth table listing the output for every combination of inputs.

**NOT** (an inverter) has one input and flips it. It is written as A′ or ¬A.

```
A | NOT A
0 |   1
1 |   0
```

**AND** outputs 1 only if *all* its inputs are 1. It is written A · B, or just AB.

**OR** outputs 1 if *at least one* input is 1. It is written A + B. Note that 1 + 1 = 1 here: this is logic, not ordinary addition.

**XOR** (exclusive OR) outputs 1 if the inputs are *different*. It is written A ⊕ B.

```
A B | AND  OR  XOR  NAND  NOR
0 0 |  0   0    0    1     1
0 1 |  0   1    1    1     0
1 0 |  0   1    1    1     0
1 1 |  1   1    0    0     0
```

**NAND** and **NOR** are AND and OR followed by NOT. They look like afterthoughts, but they are central to real chips, as you will see.

With n inputs, a truth table has 2ⁿ rows, the same counting rule as for binary numbers. A three-input function has 8 rows.

### From words to logic

The motor example becomes:

```
M = S · G · E′

S = start pressed, G = guard closed, E = emergency stop pressed
```

The motor runs only when S and G are 1 and E is 0. You could build this from one NOT gate and a three-input AND gate. In C or Python it is the same expression: `run = start and guard and not estop`.

### The laws of Boolean algebra

Boolean expressions can be rearranged with laws, much like ordinary algebra. The most useful:

```
Identity        A · 1 = A          A + 0 = A
Null            A · 0 = 0          A + 1 = 1
Idempotent      A · A = A          A + A = A
Complement      A · A′ = 0         A + A′ = 1
Double NOT      (A′)′ = A
Commutative     A · B = B · A      A + B = B + A
Distributive    A · (B + C) = A · B + A · C
Absorption      A + A · B = A      A · (A + B) = A
De Morgan       (A · B)′ = A′ + B′
                (A + B)′ = A′ · B′
```

Each law can be proved by checking every row of a truth table, because there are only finitely many combinations. For example, A + 1 = 1 says "anything OR true is true", which you can confirm for A = 0 and A = 1.

**De Morgan's laws** deserve special attention. In words: "not (A and B)" is the same as "(not A) or (not B)". "It is not the case that both doors are closed" means "at least one door is open". To apply them, break the bar, and swap AND for OR (or OR for AND).

### Simplifying a circuit

Why bother with algebra? Because a simpler expression needs fewer gates: cheaper, faster and easier to check. Suppose a warning lamp L should light under three conditions, written straight from a specification:

```
L = A · B · C + A · B · C′ + A · B′ · C
```

As written, that is three three-input AND gates, an OR gate and two NOT gates. Simplify step by step:

```
A · B · C + A · B · C′  = A · B · (C + C′)   distributive
                        = A · B · 1          complement
                        = A · B              identity

L = A · B + A · B′ · C
  = A · (B + B′ · C)                         distributive
  = A · (B + C)                              because B + B′ · C = B + C
```

The last step is worth checking with a truth table: if B is 1, both sides are 1; if B is 0, both sides equal C. So the lamp lights when A is on and either B or C is. The final circuit needs one OR gate and one AND gate. Always check a simplification against the original's truth table; it is easy to slip.

Python can generate truth tables and check laws by trying every input:

```python
from itertools import product

def table(name, f):
    print(name)
    print("A B | out")
    for a, b in product((0, 1), repeat=2):
        print(f"{a} {b} |  {f(a, b)}")

table("XOR", lambda a, b: a ^ b)

# Check De Morgan's law for every input combination
same = all((1 - (a & b)) == ((1 - a) | (1 - b)) for a, b in product((0, 1), repeat=2))
print("NOT(A AND B) == (NOT A) OR (NOT B):", same)
```

Output:

```
XOR
A B | out
0 0 |  0
0 1 |  1
1 0 |  1
1 1 |  0
NOT(A AND B) == (NOT A) OR (NOT B): True
```

Here `&`, `|` and `^` are Python's bitwise AND, OR and XOR, and `1 - a` flips a single bit.

### NAND: the universal gate

Remarkably, every logic function can be built from NAND gates alone:

```
NOT A   = A NAND A
A AND B = (A NAND B) NAND (A NAND B)      a NAND followed by a NOT
A OR B  = (A NAND A) NAND (B NAND B)      De Morgan: (A′ · B′)′ = A + B
```

The same is true of NOR. This matters in practice because in the common chip technology, CMOS, NAND and NOR gates are among the simplest and fastest to make. A chip designer can build an entire processor from huge numbers of one well-understood cell. It also means a student with a bag of identical NAND chips can, in principle, build any logic circuit.

### Gates in real hardware

Physically, a gate is a handful of transistors acting as switches. Its output is a voltage: near the supply for a 1, near ground for a 0, within the logic levels from the previous lesson. Each gate takes a few nanoseconds or less to respond, a delay that becomes important when gates are chained, as the next lesson shows. Today, most logic in a robot lives inside microcontrollers and programmable chips rather than in separate gate chips, but it is exactly the same logic, and when you write `if (a && !b)` in firmware you are writing Boolean algebra.

### Recap

- NOT flips; AND needs all inputs 1; OR needs at least one; XOR needs them different; NAND and NOR are inverted AND and OR.
- A truth table lists the output for all 2ⁿ input combinations and completely defines a function.
- Boolean laws, especially distributive, complement, absorption and De Morgan, simplify expressions to use fewer gates.
- Check every simplification against a truth table.
- NAND alone, or NOR alone, can build any logic function.

#### Project: Paper and Python project: a safety interlock

A machine has three inputs: S (start pressed), G (guard closed) and E (emergency stop pressed). Its output M enables the machine.

1. Write a specification in words: M should be 1 only when S and G are 1 and E is 0. Write the Boolean expression.
2. Write out the full 8-row truth table by hand.
3. Using the NAND constructions in this lesson, rewrite your expression using only NAND gates. Draw both the original and the NAND-only version as gate diagrams.
4. Adapt the Python truth-table code in this lesson to three inputs, and use it to check that your two versions agree on all 8 rows.
5. Simplify L = A · B + A · B′ and A + A′ · B by hand, and check both with Python.

No hardware is needed for this project.

**Deliverables**

- The Boolean expression and its 8-row truth table
- Gate diagrams for the original and NAND-only versions
- A Python check that all versions agree
- Two simplifications with working and Python checks

#### Check your understanding

1. Which gate outputs 1 only when its two inputs are different?
   A) AND
   B) OR
   C) NAND
   D) XOR

2. What is (A + B)′ by De Morgan's law?
   A) A′ + B′
   B) A′ · B′
   C) A · B
   D) A + B

3. Simplify A · B + A · B′.
   A) A
   B) B
   C) A · B
   D) 1

4. How many rows does a truth table for a four-input function have?
   A) 4
   B) 8
   C) 16
   D) 32

5. Why is NAND called a universal gate?
   A) It is the only gate that works at 3.3 V
   B) Any logic function, including NOT, AND and OR, can be built using NAND gates alone
   C) It outputs 1 for every input
   D) It can store a bit

**Go further:**

- Wikipedia — Boolean algebra: https://en.wikipedia.org/wiki/Boolean_algebra — The full set of laws, with proofs by truth table and the history of Boole's work.


## 1.5 Combinational logic: adders, multiplexers and decoders

*How gates combine into circuits that do useful work: adding binary numbers, choosing between signals and selecting one device out of many.* (about 30 min)

### Building blocks from gates

Gates on their own make simple decisions. Combine them and you get circuits that add numbers, route signals and pick which device on a bus should listen. These circuits sit inside every microcontroller: the processor's arithmetic unit is built from adders, and the logic that selects a memory location or a peripheral is built from decoders and multiplexers.

All the circuits in this lesson are **combinational**: their outputs depend only on their *current* inputs. Change the inputs and, after a short delay, the outputs follow. They have no memory of what happened before. Circuits with memory, called sequential circuits, are the subject of the next lesson.

### Adding binary numbers by hand

Binary addition follows the same column method as decimal, but carries happen whenever a column reaches 2:

```
0 + 0 = 0
0 + 1 = 1
1 + 1 = 10   (write 0, carry 1)
1 + 1 + 1 = 11   (write 1, carry 1)
```

Adding 5 (0101) and 3 (0011):

```
  carries   1 1 1
            0 1 0 1     (5)
          + 0 0 1 1     (3)
          ---------
            1 0 0 0     (8)
```

The rightmost column is 1 + 1 = 10, so write 0 and carry 1. The next is 0 + 1 + 1 = 10 again, and so on.

### The half adder

Start with the smallest piece: adding two single bits, A and B. There are two outputs, the **sum** bit S and the **carry** bit C:

```
A B | C S
0 0 | 0 0
0 1 | 0 1
1 0 | 0 1
1 1 | 1 0
```

Compare these columns with the gate truth tables from the last lesson. The sum is 1 when the inputs are different: that is **XOR**. The carry is 1 only when both are 1: that is **AND**.

```
S = A ⊕ B
C = A · B
```

Two gates, and you have a circuit that adds. It is called a **half adder** because it cannot accept a carry coming in from a previous column.

### The full adder

Every column except the first must also add the carry from the column to its right. A **full adder** adds three bits: A, B and a carry in, Cin. It produces a sum S and a carry out, Cout:

```
S    = A ⊕ B ⊕ Cin
Cout = A · B + Cin · (A ⊕ B)
```

Read the carry expression in words: there is a carry out if A and B are both 1, or if exactly one of them is 1 and a carry came in. The sum is 1 when an odd number of the three inputs are 1, which is exactly what a chain of XORs computes.

A full adder can be built from two half adders and an OR gate, which is two XORs, two ANDs and one OR in total.

### The ripple-carry adder

To add 4-bit numbers, chain four full adders. Each one's carry out feeds the next one's carry in, from the least significant bit to the most. The carry "ripples" along the chain, giving the name **ripple-carry adder**. The final carry out is a fifth bit: if it is 1, the result was too big for four bits.

Here is a ripple-carry adder simulated in Python, bit by bit:

```python
def full_adder(a, b, carry_in):
    s = a ^ b ^ carry_in
    carry_out = (a & b) | (carry_in & (a ^ b))
    return s, carry_out

def ripple_add(a_bits, b_bits):
    """Add two equal-length bit lists, least significant bit first."""
    carry, result = 0, []
    for a, b in zip(a_bits, b_bits):
        s, carry = full_adder(a, b, carry)
        result.append(s)
    return result, carry

def to_bits(n, width):
    return [(n >> i) & 1 for i in range(width)]   # LSB first

def show(bits):
    return "".join(str(b) for b in reversed(bits))  # print MSB first

for x, y in [(5, 3), (9, 6), (12, 7)]:
    total, carry = ripple_add(to_bits(x, 4), to_bits(y, 4))
    print(f"{show(to_bits(x, 4))} + {show(to_bits(y, 4))} = "
          f"carry {carry}, sum {show(total)}  ({x} + {y} = {x + y})")
```

Output:

```
0101 + 0011 = carry 0, sum 1000  (5 + 3 = 8)
1001 + 0110 = carry 0, sum 1111  (9 + 6 = 15)
1100 + 0111 = carry 1, sum 0011  (12 + 7 = 19)
```

The last line is worth studying. 12 + 7 = 19 does not fit in four bits (the maximum is 15). The four sum bits show 0011, which is 3, and the carry out is 1, worth 16: 16 + 3 = 19. If a program ignores that carry, it gets 3, which is how integer overflow happens in real processors.

### Speed: why ripple is slow

Every gate takes a little time to respond, called its **propagation delay**. In a ripple-carry adder, the top bit cannot be correct until the carry has passed through every stage below it. A 32-bit ripple adder must wait for the carry to cross 32 full adders. Real processors use cleverer **carry-lookahead** designs that work out the carries in parallel, using more gates to save time. It is a classic engineering trade-off: area against speed.

### Multiplexers: choosing a signal

A **multiplexer**, or **mux**, is a digital selector switch. A 2-to-1 mux has two data inputs, A and B, one **select** input S, and one output Y. When S is 0 the output copies A; when S is 1 it copies B:

```
Y = S′ · A + S · B
```

Read it as: "(not S and A) or (S and B)". Only one of the two AND terms can be active at a time, so the select line decides which input gets through.

With two select lines you can choose among four inputs (a 4-to-1 mux); with three, among eight. In general, n select lines choose among 2ⁿ inputs. Microcontrollers use multiplexers everywhere. A single analogue-to-digital converter is often shared between many input pins by a mux, and many pins can be switched between several internal functions, such as plain input/output or a serial port, by multiplexers controlled from software.

### Decoders: selecting one of many

A **decoder** does the reverse job: it takes an n-bit binary number and turns on exactly one of 2ⁿ outputs. A 2-to-4 decoder with inputs A1 and A0:

```
A1 A0 | Y0 Y1 Y2 Y3
 0  0 |  1  0  0  0
 0  1 |  0  1  0  0
 1  0 |  0  0  1  0
 1  1 |  0  0  0  1

Y0 = A1′ · A0′    Y1 = A1′ · A0    Y2 = A1 · A0′    Y3 = A1 · A0
```

Each output is a single AND gate that recognises one pattern. Decoders are how a processor selects one memory chip or one peripheral out of many: the address bits go into a decoder, and only the device whose output is active responds. A display driver that lights one digit at a time uses the same idea.

### Designing your own

The method for any combinational circuit is the same:

1. Write the specification in words.
2. Turn it into a truth table covering every input combination.
3. Write an expression for each output, for example by OR-ing together an AND term for each row where the output is 1.
4. Simplify with Boolean algebra.
5. Check the simplified version against the truth table.

### Recap

- Combinational circuits have outputs that depend only on their present inputs, with no memory.
- A half adder is an XOR (sum) and an AND (carry); a full adder adds a carry in as well.
- Chaining full adders makes a ripple-carry adder; the final carry out signals that the result overflowed.
- Propagation delay means ripple adders get slower as they get wider.
- A multiplexer selects one of 2ⁿ inputs using n select lines; a decoder activates one of 2ⁿ outputs from an n-bit number.

#### Project: Paper and Python project: build and test an adder

1. Fill in the full 8-row truth table of a full adder by hand, from the definition (add three bits, write the two-bit result).
2. Check that the expressions S = A ⊕ B ⊕ Cin and Cout = A · B + Cin · (A ⊕ B) give the same table.
3. Extend the Python ripple adder in this lesson to 8 bits, and write a loop that checks every pair of numbers from 0 to 255 against Python's own `+` (remember to include the carry out as bit 8).
4. Write a Python function for a 2-to-1 multiplexer using only `&`, `|` and `1 - s`, and test all 8 combinations of A, B and S.
5. Draw the gate diagram of a 2-to-4 decoder.

No hardware is needed for this project.

**Deliverables**

- Full adder truth table checked against the expressions
- An 8-bit ripple adder that passes all 65,536 tests
- A tested multiplexer function
- A decoder gate diagram

#### Check your understanding

1. Which pair of gates makes a half adder?
   A) OR for the sum, AND for the carry
   B) AND for the sum, XOR for the carry
   C) XOR for the sum, AND for the carry
   D) NAND for the sum, NOR for the carry

2. A full adder has A = 1, B = 0 and Cin = 1. What are S and Cout?
   A) S = 0, Cout = 1
   B) S = 1, Cout = 0
   C) S = 1, Cout = 1
   D) S = 0, Cout = 0

3. A 4-bit ripple-carry adder adds 1010 and 1000. What happens?
   A) The sum bits are 0010 and the carry out is 1, because 10 + 8 = 18 does not fit in four bits
   B) The sum bits are 1010 and the carry out is 0
   C) The adder outputs 18 on four bits
   D) The adder stops working

4. How many select lines does a multiplexer need to choose among 16 inputs?
   A) 16
   B) 8
   C) 2
   D) 4

5. What makes a circuit combinational rather than sequential?
   A) It uses only NAND gates
   B) Its outputs depend only on its present inputs, with no memory of past inputs
   C) It runs from a clock
   D) It has more than one output

**Go further:**

- Wikipedia — Adder (electronics): https://en.wikipedia.org/wiki/Adder_(electronics) — Half adders, full adders, ripple-carry and faster carry-lookahead designs, with truth tables.


## 1.6 Sequential logic: latches, flip-flops and clocks

*How circuits remember: the latch, the edge-triggered flip-flop, registers and counters, and the clock that keeps a whole chip in step.* (about 30 min)

### Circuits that remember

An adder forgets everything the moment its inputs change. But a robot needs memory: how many encoder pulses have arrived, which step of a sequence it is on, what value was just read from a sensor. A processor is mostly memory with some logic in between. **Sequential logic** is logic whose outputs depend on the present inputs *and* on what happened before. This lesson shows how memory is built from gates, and why almost all of it is controlled by a **clock**.

### Feedback makes memory

The trick is to feed a gate's output back into its own inputs. The classic example is the **SR latch** (set–reset), made from two NOR gates, each with its output wired to one input of the other. It has two inputs, S and R, and an output Q (plus its opposite, Q′):

```
S R | Q after
0 0 | Q unchanged   (hold: the latch remembers)
1 0 | 1             (set)
0 1 | 0             (reset)
1 1 | not allowed   (both outputs forced to 0)
```

Pulse S to 1 and Q becomes 1. Let S go back to 0 and Q *stays* 1, because the cross-coupled gates hold each other in that state. Pulse R and Q becomes 0, and stays 0. That is one bit of memory, made from two gates. The row S = R = 1 is avoided because it forces both outputs to 0, breaking the rule that Q′ is the opposite of Q, and when both inputs are released together the final state is unpredictable.

### The D latch

Designers usually want something simpler to use: "store this bit". The **D latch** has a data input D and an enable input E. While E is 1, the output Q follows D. When E goes to 0, Q freezes at whatever D was at that moment. Inside, it is an SR latch with a little logic in front that makes the forbidden state impossible.

Because the output follows the input for the whole time E is 1, a D latch is called **transparent**. That can be a problem: if D changes several times while E is high, the change passes straight through, and in a large circuit signals can race around loops in ways that are hard to predict.

### The edge-triggered flip-flop

The solution is to capture the input at a single instant. A **D flip-flop** has a data input D and a **clock** input. It copies D to Q only at the moment the clock rises from 0 to 1, called the **rising edge**. At all other times Q holds its value, whatever D does.

```
clock:  ___|‾‾‾|___|‾‾‾|___|‾‾‾|___
D:      1   0       1   1       0
Q:      captures D at each rising edge, holds in between
```

This one idea makes large digital systems possible. Every flip-flop in a chip samples its input at the same clock edge. Between edges, the combinational logic has time to work out the next values. At the next edge, everything updates together. The whole chip moves in lock-step, one clock tick at a time. This is called **synchronous** design.

### Timing: setup and hold

A flip-flop needs its input to be steady for a short time *before* the clock edge (the **setup time**) and just *after* it (the **hold time**). If D changes too close to the edge, the flip-flop may take an unpredictable time to settle, a condition called **metastability**.

This sets a chip's speed limit. Between two clock edges, signals must travel out of one flip-flop, through the slowest path of combinational logic, and arrive at the next flip-flop at least one setup time before the edge. If the clock is faster than that, the chip computes wrong answers. This is why the long carry chain of a ripple adder, from the last lesson, limits how fast a clock can run.

### The clock

The **clock** is a signal that switches between 0 and 1 at a steady rate. Its **frequency** is how many cycles happen per second, measured in hertz (Hz); its **period** is the time for one cycle:

```
period = 1 / frequency
```

A microcontroller running at 16 MHz has a clock period of 1 / 16,000,000 s = 62.5 nanoseconds. A desktop processor at 3 GHz has a period of about 0.33 ns. Clocks usually come from a quartz crystal or an on-chip oscillator, and on-chip circuits can multiply or divide them to give different parts of the chip the speeds they need.

### Registers

Put several D flip-flops side by side, all sharing one clock, and you have a **register**: a circuit that stores a multi-bit value. An 8-bit register is eight flip-flops and stores one byte. A processor's working registers, a peripheral's control registers and the output pins of a microcontroller are all registers. When firmware writes 0x3F to a configuration register, it is setting the D inputs of eight flip-flops, which capture the pattern on the next clock edge and hold it until they are written again.

A **shift register** connects each flip-flop's output to the next one's input, so on every clock edge the stored bits move one place along. Shift registers turn data arriving one bit at a time into a parallel byte, and back again, which is exactly what serial communication hardware does.

### Counters

A **counter** is a register whose next value is its current value plus one. It combines flip-flops (memory) with an adder (combinational logic): on each clock edge, the register captures the output of an adder that adds 1 to the register's current contents.

For a 3-bit counter, the next-state logic for each flip-flop can be written directly. Bit 0 flips every time; bit 1 flips when bit 0 is 1; bit 2 flips when bits 1 and 0 are both 1, exactly like carries rippling in an adder. This Python program simulates it:

```python
def next_state(q):
    """Next-state logic for a 3-bit counter: the D inputs of three flip-flops."""
    q0, q1, q2 = q
    d0 = 1 - q0
    d1 = q1 ^ q0
    d2 = q2 ^ (q1 & q0)
    return (d0, d1, d2)

q = (0, 0, 0)                         # the flip-flops start cleared
for edge in range(10):
    value = q[0] + 2 * q[1] + 4 * q[2]
    print(f"after {edge} clock edges: Q2 Q1 Q0 = {q[2]}{q[1]}{q[0]}  ({value})")
    q = next_state(q)                 # every flip-flop updates on the same edge
```

Output:

```
after 0 clock edges: Q2 Q1 Q0 = 000  (0)
after 1 clock edges: Q2 Q1 Q0 = 001  (1)
after 2 clock edges: Q2 Q1 Q0 = 010  (2)
after 3 clock edges: Q2 Q1 Q0 = 011  (3)
after 4 clock edges: Q2 Q1 Q0 = 100  (4)
after 5 clock edges: Q2 Q1 Q0 = 101  (5)
after 6 clock edges: Q2 Q1 Q0 = 110  (6)
after 7 clock edges: Q2 Q1 Q0 = 111  (7)
after 8 clock edges: Q2 Q1 Q0 = 000  (0)
after 9 clock edges: Q2 Q1 Q0 = 001  (1)
```

The line `q = next_state(q)` matters: all three new values are computed from the *old* state and then stored together, which is what a shared clock edge does. After 7 the counter **wraps** to 0, because 3 bits can only hold 0 to 7.

Notice also how often each bit changes. Q0 flips on every edge, so it completes one full cycle every 2 clock edges: its frequency is half the clock's. Q1 runs at a quarter, and Q2 at an eighth. A counter is therefore also a **frequency divider**. A 4-bit counter driven at 16 MHz has a top bit running at 16 / 2⁴ = 1 MHz.

Counters like this are the heart of a microcontroller's **timers**, which count clock edges to measure time, generate regular interrupts and produce PWM signals for motors and LEDs. When you meet timers in the microcontrollers module, you will be looking at a counter, a register to compare it against, and a little logic.

### Recap

- Sequential logic has memory: outputs depend on past inputs as well as present ones.
- Feedback between gates makes an SR latch, which can hold one bit; a D latch is easier to use but transparent while enabled.
- A D flip-flop captures its input only at the clock's rising edge, which lets a whole chip update in lock-step.
- Setup and hold times, plus logic delays, set the maximum clock frequency.
- Period = 1 / frequency; 16 MHz gives 62.5 ns.
- Registers store multi-bit values; counters add one each clock edge, wrap round at 2ⁿ, and divide frequencies by powers of two.

#### Project: Paper and Python project: counters and dividers

1. Draw a timing diagram by hand for the 3-bit counter in this lesson: one row each for the clock, Q0, Q1 and Q2, over 10 clock edges. Mark where each output changes.
2. Change the Python simulation to a 4-bit counter. After how many edges does it wrap?
3. Modify the counter so that it counts down instead of up. (Hint: work out when each bit should flip.)
4. Make a counter that counts 0 to 5 and then returns to 0 (a modulo-6 counter), by detecting the value 5 and forcing the next state to 0.
5. A microcontroller's clock is 8 MHz. What is its period? What frequency comes out of the top bit of a 10-bit counter driven by it?

No hardware is needed for this project.

**Deliverables**

- A hand-drawn timing diagram for the 3-bit counter
- Working 4-bit up, down and modulo-6 counter simulations with their output
- The period and divided frequency calculations

#### Check your understanding

1. An SR latch has Q = 1. Both S and R are now 0. What is Q?
   A) 0
   B) Unpredictable
   C) 1, because the latch holds its previous state
   D) It oscillates

2. What is the key difference between a D latch and a D flip-flop?
   A) A latch stores more bits
   B) A flip-flop captures D only at a clock edge, while a latch passes D through for as long as it is enabled
   C) A flip-flop has no memory
   D) A latch needs a clock and a flip-flop does not

3. What is the clock period of a microcontroller running at 20 MHz?
   A) 50 ns
   B) 20 ns
   C) 5 ns
   D) 0.05 ns

4. A 4-bit counter starts at 0. What value does it hold after 18 clock edges?
   A) 18
   B) 15
   C) 0
   D) 2

5. Why must the clock not run faster than a certain limit?
   A) Faster clocks always overheat the chip instantly
   B) Signals need time to pass through the slowest logic path and settle before the next clock edge, including the setup time
   C) Flip-flops can only count to 255
   D) The clock must match the supply voltage

**Go further:**

- Wikipedia — Flip-flop (electronics): https://en.wikipedia.org/wiki/Flip-flop_(electronics) — Latches and flip-flops of every type, with timing considerations including setup, hold and metastability.


---

# Module 2: Microcontrollers

What a microcontroller is, what is inside one, and how it differs from the computer on your desk.

**Objectives**

- Identify the main parts of a microcontroller: processor core, memory, clock and peripherals.
- Compare microcontrollers with general-purpose computers in cost, power and capability.
- Explain the role of general-purpose input/output pins.
- Describe how a program is stored and run after power-up.


## 2.1 Inside a microcontroller

*The processor core, flash, RAM, peripherals and clock packed onto one small chip, what happens when it powers up, and how it differs from the computer on your desk.* (about 25 min)

### A computer you never see

A robot gripper has to read its force sensor hundreds of times per second, decide whether the grip is tight enough, and adjust a motor, without ever freezing, rebooting for updates or waiting for a mouse click. The device doing that job is almost never a laptop. It is a **microcontroller**: a complete, small computer on a single chip, often smaller than a fingernail and cheap enough to put inside a toothbrush.

Microcontrollers are everywhere: in washing machines, keyboards, thermostats and servo-driven robot joints. You already know from the digital electronics module how bits, gates and flip-flops behave. A microcontroller is what you get when you organise enormous numbers of them with purpose.

### The five main parts

Every microcontroller, whichever company makes it, contains the same basic building blocks.

**1. The CPU core.** The processor runs your program one instruction at a time, endlessly repeating a cycle: *fetch* the next instruction from memory, *decode* what it means, *execute* it. Instructions are tiny steps such as "add these two numbers" or "jump back to line 12 if the result was zero". The core holds a few **registers**, very fast storage slots built from flip-flops, where it keeps the numbers it is working on right now. Cores are described by how many bits they handle at once: 8-bit, 16-bit and 32-bit cores are all common.

**2. Flash memory.** This is where your program lives. Flash is *non-volatile*: it keeps its contents when the power is off, which is why a microcontroller runs the same program every time you switch it on. Typical sizes range from a few kilobytes to a few megabytes.

**3. RAM.** Random-access memory holds the variables your program changes while running: sensor readings, counters, the current state of a motor. RAM is *volatile*: everything in it vanishes when the power goes. It is also small, often between 1 KB and a few hundred KB. Your laptop has around a million times more.

**4. Peripherals.** These are dedicated hardware blocks that handle jobs the CPU would be slow or clumsy at:

- **GPIO** (general-purpose input/output) pins that can be switched high or low, or read
- **Timers** that count clock pulses, measure time and generate signals
- **ADCs** (analog-to-digital converters) that measure voltages
- **Communication** blocks such as UART, I2C and SPI for talking to sensors and other chips
- **PWM** outputs for dimming lights and controlling motor speed

You will meet most of these later in this module. The important idea is that peripherals work *in parallel* with the CPU. A timer keeps counting while the CPU does arithmetic.

**5. The clock.** A clock signal, a square wave, steps the whole chip forward. It might come from a small quartz crystal outside the chip (accurate) or from an internal oscillator (cheaper, less accurate). Clock speeds are usually measured in megahertz (MHz), millions of cycles per second.

### Worked example: how much time is a clock cycle?

Suppose a microcontroller runs at 16 MHz. One cycle takes:

```
1 / 16 000 000 Hz = 0.0000000625 s = 62.5 ns
```

If your control loop must run 1,000 times per second (1 kHz), each pass has 1 ms available. In cycles:

```
16 000 000 cycles/s × 0.001 s = 16 000 cycles per loop
```

If simple instructions take one or two cycles, that is several thousand instructions per loop: plenty for reading a sensor and some arithmetic, nowhere near enough for processing a camera image. Quick budgets like this are a core embedded habit.

### How the CPU talks to peripherals

Here is a neat trick. Peripherals are controlled through special memory locations called **registers** (a second meaning of the word). The CPU writes a number to a particular address, and instead of storing it like RAM, the hardware reacts: a pin goes high, a timer starts. Reading another address tells you whether a button pin is high or low. This is called **memory-mapped I/O**. Each chip's **datasheet** lists these addresses and what each bit means. You will learn to read those register descriptions in the programming foundations module.

### What happens at power-up

When power arrives, a **reset** circuit holds the chip still until the voltage is stable. Then the CPU reads a fixed location in flash, the **reset vector**, which tells it where the start-up code is. That start-up code sets up the stack, copies the starting values of variables into RAM, sets the rest to zero, and calls your `main` function. There is no operating system to return to, so a microcontroller program normally ends in a loop that runs forever. Power off, power on, and the whole sequence repeats exactly.

### How it differs from your computer

- **Speed:** tens to hundreds of MHz, against several GHz in a laptop.
- **Memory:** kilobytes of RAM, against gigabytes.
- **Operating system:** usually none (called *bare metal*), or a tiny real-time operating system. Your code owns the whole chip.
- **Timing:** predictable. With no background updates or other programs competing, the same code takes the same time every pass. Engineers call this *deterministic*.
- **Power:** a few milliamps while running and often microamps while asleep, so it can run for months on small batteries.
- **Direct hardware access:** pins connect straight to the outside world.

A **single-board computer** sits in between: a full processor with an operating system on a small board. Robots often use both: a single-board computer for vision and planning, and microcontrollers for fast, reliable jobs such as motor control. The robotic system architecture module discusses how to split the work.

One well-known example: the original Arduino Uno board uses an 8-bit ATmega328P microcontroller running at 16 MHz with 32 KB of flash and 2 KB of RAM. That is enough to run thousands of hobby robots.

### Recap

A microcontroller is a whole computer on one chip: a CPU core that fetches and executes instructions, flash that keeps the program, RAM that holds changing variables, peripherals that do hardware jobs in parallel, and a clock that paces it all. It starts from the reset vector, runs `main` forever, and trades raw power for low cost, low energy use and predictable timing.

> **Typical numbers, not rules.** The sizes and speeds in this lesson are typical ranges, chosen so you can estimate. Real chips vary widely, and the only authority on a specific chip is its own datasheet. Get into the habit of checking it.

#### Project: Paper project: a memory and time budget

Imagine a microcontroller with **32 KB of flash**, **2 KB of RAM** (2,048 bytes) and a **16 MHz** clock. You want to store the last 500 force readings, each a 2-byte number, so you can send them to a laptop later.

1. How many bytes of RAM does the buffer need? What fraction of RAM is that?
2. Engineers like to keep spare RAM for the stack and other variables. Would you be comfortable with this design? What would you change if you needed 2,000 readings?
3. You sample at 500 readings per second. How many clock cycles are available between readings?

Show every step and its units.

**Deliverables**

- The RAM calculation with units and the fraction of RAM used
- A short judgement on whether the design leaves enough margin, with one alternative
- The number of clock cycles between readings

#### Check your understanding

1. Your program's code must still be there after the power is switched off and on again. Where is it stored?
   A) RAM
   B) Flash memory
   C) The CPU's registers
   D) The clock

2. A microcontroller runs at 8 MHz. How long is one clock cycle?
   A) 8 ns
   B) 80 ns
   C) 125 ns
   D) 1.25 µs

3. What does memory-mapped I/O mean?
   A) Peripherals are controlled by reading and writing special addresses, called registers
   B) The program is copied from RAM to flash at start-up
   C) The microcontroller stores a map of the room
   D) Every pin has its own small CPU

4. Why do many robots use a microcontroller for motor control even when they also carry a powerful single-board computer?
   A) Microcontrollers are always faster than single-board computers
   B) Single-board computers cannot run C programs
   C) Microcontrollers have more RAM
   D) Microcontrollers give predictable timing and direct hardware access, without an operating system interrupting

5. What happens first when a microcontroller comes out of reset?
   A) It waits for a user to press start
   B) It reads the reset vector to find the start-up code, which eventually calls main
   C) It downloads its program from the internet
   D) It runs main, then shuts down when main returns

**Go further:**

- Microcontroller (Wikipedia): https://en.wikipedia.org/wiki/Microcontroller — An overview of microcontroller history, architecture and typical peripherals.


## 2.2 Digital input and output with GPIO

*Configuring general-purpose pins as outputs or inputs, driving an LED safely, reading a switch, and respecting the current limits that keep a chip alive.* (about 25 min)

### The microcontroller's fingertips

A robot's microcontroller has to switch on a warning light, sense whether a limit switch has been hit, and enable a motor driver. All three jobs use the simplest peripheral of all: **general-purpose input/output**, or **GPIO**. Each GPIO pin is a single wire between the chip and the outside world that can either *drive* a voltage (output) or *sense* one (input). Getting GPIO right, including its electrical limits, is the foundation for everything else in this module.

### Outputs: driving a pin high or low

When a pin is configured as an **output**, your program decides its level:

- **High** (logic 1): the pin is connected internally to the chip's supply, so it sits near that voltage, commonly 3.3 V or 5 V.
- **Low** (logic 0): the pin is connected to ground, near 0 V.

Inside, a pair of transistors act as switches, one to the supply and one to ground. When the pin pushes current *out* to a load it is **sourcing** current; when current flows *into* it, it is **sinking** current.

### Inputs: reading a level

Configured as an **input**, a pin becomes a sensor. It draws almost no current (its *impedance* is very high) and simply compares the voltage on it with thresholds. From the digital electronics module you know that a voltage near the supply reads as 1 and near ground reads as 0, with an uncertain band in between. A pin that is not connected to anything, a **floating** input, can read either value at random, picking up stray electric fields from your hand or nearby wires. The next lesson shows how to fix that.

### Configuring pins in code

Every pin must be told its job, usually once at start-up. Each manufacturer provides a library with its own function names. The code below uses **generic illustrative names**: `gpio_set_mode`, `gpio_write`, `gpio_read` and `delay_ms` stand in for whatever your board's library provides. The structure is the same everywhere.

```c
/* Illustrative only: gpio_set_mode, gpio_write and delay_ms
   stand in for the functions your board's library provides. */
#define LED_PIN 13

int main(void) {
    gpio_set_mode(LED_PIN, GPIO_OUTPUT);
    while (1) {
        gpio_write(LED_PIN, 1);   /* pin goes high: LED on  */
        delay_ms(500);
        gpio_write(LED_PIN, 0);   /* pin goes low:  LED off */
        delay_ms(500);
    }
}
```

This is the embedded "hello world": a blinking light, one second per cycle. Reading an input looks similar:

```c
/* Illustrative only: names stand in for your board's library. */
#define LED_PIN     13
#define SWITCH_PIN  2

int main(void) {
    gpio_set_mode(LED_PIN, GPIO_OUTPUT);
    gpio_set_mode(SWITCH_PIN, GPIO_INPUT);

    while (1) {
        int level = gpio_read(SWITCH_PIN);   /* 0 or 1 */
        gpio_write(LED_PIN, level);          /* copy the switch to the LED */
    }
}
```

Under the hood, each of these calls writes or reads bits in a peripheral register, as described in the previous lesson. You will do that directly in the bitwise operations lesson.

### Driving an LED: the series resistor

An LED (light-emitting diode) is not like a resistor. Once the voltage across it reaches its **forward voltage**, roughly 1.8 to 2.2 V for many red LEDs and around 3 V for many blue and white ones, its current rises very steeply. Connect it straight to a pin and the current is limited only by the pin's internal resistance: the LED, the pin or both can be damaged. So we add a **series resistor** to set the current.

The resistor has whatever voltage is left over after the LED takes its share. With Ohm's law:

```
R = (V_supply − V_LED) / I
```

### Worked example

A 3.3 V output drives a red LED with a forward voltage of about 2.0 V. We want about 5 mA, which is plenty for an indicator light.

```
R = (3.3 V − 2.0 V) / 0.005 A = 1.3 V / 0.005 A = 260 Ω
```

Resistors come in standard values, so pick the next one up, 270 Ω. Check the actual current:

```
I = 1.3 V / 270 Ω ≈ 0.0048 A = 4.8 mA
```

Rounding *up* the resistance always makes the current slightly smaller, which is the safe direction. The resistor dissipates P = V × I = 1.3 × 0.0048 ≈ 0.006 W, far below what even a tiny resistor can handle.

### Current limits: the rule that saves chips

Every datasheet lists an **absolute maximum** current per pin and a total for the chip or for groups of pins, commonly a few milliamps to a few tens of milliamps per pin. Two practical rules:

- **Design well below the maximum.** The absolute maximum is the point where damage may begin, not a recommended operating level.
- **Add up all your pins.** Eight LEDs at 10 mA each is 80 mA, which may exceed the chip's total even if each pin is fine.

A GPIO pin must **never** power a motor, a relay coil or a speaker directly. Motors need far more current than a pin can give, and when a coil switches off it produces a voltage spike that can destroy the pin. Instead, the pin controls a **driver**, such as a transistor or a motor driver chip, which switches the large current from a separate supply. The pin only provides a small control signal.

One more trap: voltage levels. A 5 V signal connected to a 3.3 V microcontroller's input can damage it unless the datasheet says that pin is *5 V tolerant*. When two boards with different supply voltages must talk, use a level shifter or a voltage divider.

### Recap

A GPIO pin is either an output, driving high (near the supply) or low (near ground), or an input that reads a voltage as 0 or 1. Configure each pin before you use it. Always limit LED current with a series resistor, calculated as R = (V_supply − V_LED) / I and rounded up. Respect per-pin and total current limits, use drivers for anything power-hungry, and never feed a pin more voltage than it is rated for.

> **Low voltage and supervision only.** Everything in this module uses low-voltage supplies, 5 V or less, from USB or a small battery pack. Never connect a microcontroller project to mains electricity. If you build anything with real components, work with an adult, disconnect power before changing wiring, and stop immediately if anything gets hot or smells of burning.

#### Project: Calculate LED resistors, then try it in a simulator or on the bench

Using R = (V_supply − V_LED) / I, calculate the series resistor for each case, round up to the next standard value from this list (100, 150, 220, 270, 330, 470, 680, 1000 Ω) and recompute the actual current:

1. 5.0 V supply, red LED at 2.0 V, target 10 mA.
2. 3.3 V supply, green LED at 2.2 V, target 5 mA.
3. 3.3 V supply, white LED at 3.0 V, target 3 mA.

Then write, on paper or in a free online microcontroller simulator, a program using the illustrative GPIO functions that turns on case 1's LED only while a switch input reads 1. If you build it for real, use only a USB-powered board and the resistor you calculated.

**Deliverables**

- Three resistor calculations with chosen standard values and actual currents
- A short comment on why case 3 leaves so little headroom
- Your input-to-output program, with every pin configured before use

**Safety (adult supervision required):** Real-hardware steps must be done with adult supervision, using only a USB-powered or 5 V-or-less board. Always include the series resistor, disconnect power before changing any wiring, and unplug immediately if a part becomes hot.

#### Check your understanding

1. Why can an unconnected (floating) input pin read random values?
   A) It draws so little current that stray electric fields can push its voltage either way
   B) The CPU is too slow to read it
   C) Input pins always output a square wave
   D) Floating inputs are permanently stuck at 1

2. A 5 V pin drives a red LED (forward voltage 2.0 V) at a target of 10 mA. What resistance do you calculate?
   A) 200 Ω
   B) 500 Ω
   C) 300 Ω
   D) 700 Ω

3. When choosing a standard resistor value, why round the resistance up rather than down?
   A) Larger resistors are cheaper
   B) More resistance means slightly less current, which keeps the LED and pin within limits
   C) The LED will be brighter
   D) Rounding down is not allowed by Ohm's law

4. You want a microcontroller to switch a small DC motor on and off. What is the correct approach?
   A) Connect the motor directly to a GPIO output pin
   B) Use two GPIO pins in parallel to double the current
   C) Connect the motor to an input pin instead
   D) Use the GPIO pin to control a transistor or motor driver that switches a separate supply

**Go further:**

- General-purpose input/output (Wikipedia): https://en.wikipedia.org/wiki/General-purpose_input/output — Background on GPIO pins, their configuration options and typical uses.


## 2.3 Buttons, pull-up resistors and debouncing

*Why a button needs a pull-up or pull-down resistor, how active-low logic works, and how to turn a bouncing mechanical contact into one clean press in software.* (about 30 min)

### A button is harder than it looks

A button seems like the easiest input there is: pressed or not pressed. Yet two problems catch out almost every beginner. First, a button wired to a pin with nothing else often reads random values. Second, a single press can be counted as three, five or ten presses. On a robot, that might mean an emergency-stop reset that triggers twice, or a mode button that skips straight past the mode you wanted. This lesson fixes both problems: the first with a resistor, the second with a few lines of careful code.

### Problem one: the floating input

Wire a button between a pin and ground. When pressed, it connects the pin to 0 V, which reads as 0. But when released, the pin is connected to *nothing*. As you saw in the previous lesson, a floating input can read 0 or 1 unpredictably.

The fix is a **pull-up resistor**: a resistor from the pin to the supply voltage.

- **Released:** the input pin draws almost no current, so there is almost no voltage across the resistor (V = I × R with I ≈ 0). The pin sits at the supply voltage and reads **1**.
- **Pressed:** the button connects the pin straight to ground, so it reads **0**. Current now flows from the supply, through the resistor and the button, to ground.

Notice the logic is reversed: pressed means 0. This is called **active-low**, and it is extremely common. Your code just needs to know which way round it is.

### How big should the resistor be?

With a 10 kΩ pull-up on a 3.3 V supply, the current while the button is pressed is:

```
I = 3.3 V / 10 000 Ω = 0.00033 A = 0.33 mA
```

That is tiny and wastes little energy. Compare the extremes:

- **Too small**, say 0 Ω (a plain wire): pressing the button would short the supply to ground.
- **Too large**, say 10 MΩ: the pull is so weak that tiny leakage currents and electrical noise can drag the pin below the threshold.

Values from a few kilohms to about 100 kΩ are typical, and 10 kΩ is a popular choice. A **pull-down** resistor is the mirror image: a resistor to ground and a button to the supply, giving active-high logic.

Most microcontrollers also contain **internal pull-up resistors**, often tens of kilohms, which you switch on in software when you configure the pin, for example with an illustrative mode such as `GPIO_INPUT_PULLUP`. That saves a component, though the datasheet will tell you the exact value range, which may be wide.

### Problem two: contact bounce

Inside a button, two metal contacts snap together. They do not settle instantly. They hit, spring apart, hit again, and chatter for a short time, often a few milliseconds, sometimes longer for worn or cheap switches. A microcontroller reading the pin thousands of times per second sees this chatter as a burst of separate presses. This is **contact bounce**.

A pin sampled every millisecond might see something like this during a single press and release (1 = released, 0 = pressed):

```
1 1 1 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 1 1 0 1 1 1 1 1 1
```

Count the changes from 1 to 0: there are five, but the person pressed only once.

### Fixing bounce

There are two broad approaches.

**Hardware debouncing** adds a resistor and capacitor (an RC filter) so the voltage cannot change instantly, often followed by a *Schmitt trigger* input, which has two thresholds so a slowly changing voltage produces one clean edge.

**Software debouncing** accepts a new level only after it has stayed the same for a set time. This costs no parts, so it is very common. Here is a complete, portable C version you can compile and run on any computer. It feeds in the made-up samples above, one per millisecond.

```c
#include <stdio.h>
#include <stdint.h>

#define STABLE_MS 5   /* real buttons: use 10 to 20 */

typedef struct {
    int stable;       /* debounced level: 1 = released, 0 = pressed */
    int last_raw;     /* the previous raw sample */
    uint32_t count;   /* how many ms the raw level has stayed the same */
} Debouncer;

/* Call once per millisecond with the raw pin level.
   Returns 1 exactly once per press. */
int debounce_update(Debouncer *d, int raw) {
    if (raw == d->last_raw) {
        if (d->count < STABLE_MS) d->count++;
    } else {
        d->last_raw = raw;
        d->count = 0;
    }
    if (d->count >= STABLE_MS && raw != d->stable) {
        d->stable = raw;
        return raw == 0;   /* report only the press, not the release */
    }
    return 0;
}

int main(void) {
    /* Made-up samples, one per ms: a press that bounces, then a
       release that bounces. 1 = released, 0 = pressed. */
    int raw[] = {1,1,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,
                 1,0,1,1,0,1,1,1,1,1,1,1,1,1};
    int n = sizeof raw / sizeof raw[0];
    Debouncer d = {1, 1, STABLE_MS};
    int raw_presses = 0, presses = 0;

    for (int i = 0; i < n; i++) {
        if (i > 0 && raw[i - 1] == 1 && raw[i] == 0) raw_presses++;
        if (debounce_update(&d, raw[i])) {
            presses++;
            printf("press detected at t = %d ms\n", i);
        }
    }
    printf("raw falling edges: %d, debounced presses: %d\n", raw_presses, presses);
    return 0;
}
```

Compile and run it with `cc -std=c99 -Wall debounce.c -o debounce` and then `./debounce`. The output is:

```
press detected at t = 13 ms
raw falling edges: 5, debounced presses: 1
```

The last bounce happens at t = 8 ms. The level then stays at 0 for five more samples, so the press is confirmed at 13 ms. The release bounces too, but the function deliberately reports only presses.

Two design points are worth noticing. First, the function reports an **edge**, the moment of change, not a **level**. "Do something once per press" needs edges; "keep the motor running while held" needs the level. Second, the logic does not touch any hardware: it takes a number in and returns a number. That is why you can test it on a laptop with made-up data before it ever runs on a chip. On a real board you would call it once per millisecond with `gpio_read(BUTTON_PIN)`.

The delay costs you a few milliseconds of response time, which no human will notice. Choosing the stable time is a trade-off: too short and bounce gets through; too long and quick double-presses get merged.

### Recap

An input needs a defined level at all times: a pull-up resistor (external or internal) holds it high, and the button pulls it low, giving active-low logic. Mechanical contacts bounce, so one press can look like many. Debounce in hardware with an RC filter and Schmitt trigger, or in software by accepting a level only after it has been stable for a set time. Act on edges for one-off actions and on levels for held actions.

#### Project: Experiment with the debouncer

Copy the debouncer program above into a file, compile it with `cc -std=c99 -Wall` and run it. Then experiment:

1. Change `STABLE_MS` to 2. Predict how many presses will be detected, then run it and explain the result.
2. Change it to 12. What happens now, and why?
3. Edit `debounce_update` so it also reports releases (for example by returning 2 for a release). Print both events.
4. Write your own bouncing sample array for a *double* press, two quick presses about 40 ms apart, and check that your chosen `STABLE_MS` separates them.

This is a software-only activity: no hardware is needed.

**Deliverables**

- Your predictions and actual outputs for STABLE_MS = 2 and 12, with explanations
- The modified function that reports releases
- Your double-press test data and its output

#### Check your understanding

1. A button connects a pin to ground, with a 10 kΩ pull-up resistor to 3.3 V. What does the pin read while the button is released?
   A) 0, because the button is open
   B) 1, because the resistor holds the pin near 3.3 V
   C) A random value, because the pin is floating
   D) Half of 3.3 V, which reads as neither

2. Why not use a 10 MΩ pull-up resistor to save even more current?
   A) The pull would be so weak that leakage and noise could drag the pin to the wrong level
   B) It would short the supply to ground
   C) It would make the button active-high
   D) Large resistors cannot be used with microcontrollers

3. A counter increases by 4 every time a button is pressed once. What is the most likely cause?
   A) The pull-up resistor is too small
   B) The clock is too slow
   C) Contact bounce
   D) The pin is configured as an output

4. In the software debouncer, what must happen before a new level is accepted?
   A) The button must be pressed twice
   B) The CPU must be reset
   C) The interrupt must fire
   D) The raw level must stay unchanged for STABLE_MS consecutive samples

**Go further:**

- Pull-up resistor (Wikipedia): https://en.wikipedia.org/wiki/Pull-up_resistor — How pull-up and pull-down resistors define logic levels, with circuit examples.
- Switch: contact bounce (Wikipedia): https://en.wikipedia.org/wiki/Switch#Contact_bounce — The section on contact bounce and common ways of dealing with it.


## 2.4 Timers and pulse-width modulation

*How hardware timers count clock pulses to measure time, and how pulse-width modulation uses fast on–off switching to dim LEDs and control motor speed.* (about 30 min)

### Precise time without the CPU

A robot arm's joint motor needs its power adjusted smoothly, not just switched fully on or off. A control loop must run exactly every millisecond. A status light should fade gently rather than flash. All of these depend on **timers**, among the most useful peripherals on any microcontroller. Timers count independently of the CPU, so timing stays accurate even while your program is busy. And one of their most important jobs is producing **PWM**, a trick that lets a digital pin behave almost like an adjustable voltage.

### How a timer works

A timer is a hardware counter, a register built from flip-flops, just like the counters in the sequential logic lesson. On every tick it adds one. Ticks come from the system clock, usually through a **prescaler** that divides the clock down so the counter does not race through its range too quickly.

When the counter reaches its maximum it **overflows** and starts again from zero. Many timers can also compare the count with a value you choose and do something when they match, such as setting a flag, triggering an interrupt or flipping a pin. This is a **compare match**.

### Worked example: a 1 ms tick

A chip runs at 16 MHz. Set the prescaler to 64:

```
tick rate   = 16 000 000 / 64 = 250 000 ticks per second
tick period = 1 / 250 000 = 4 µs
```

To mark every millisecond, count 1 ms / 4 µs = 250 ticks. Configure a compare match at the 250th tick (count 249, since the count starts at 0) and reset the counter each time. You now have a clock that ticks exactly every millisecond, the basis of the non-blocking timing you will meet in the programming foundations module.

How long can a 16-bit timer count with that prescaler before overflowing? It has 65,536 values:

```
65 536 × 4 µs = 262 144 µs ≈ 262 ms
```

A bigger prescaler stretches the range but makes each tick coarser. That trade-off between range and resolution shows up constantly in embedded design.

### Pulse-width modulation

A GPIO pin can only be high or low. But suppose you switch it on and off very quickly: on for one quarter of the time, off for three quarters, thousands of times per second. Anything slow to respond, such as your eye looking at an LED or the heavy rotor of a motor, experiences the **average**.

That is **pulse-width modulation (PWM)**. Two numbers describe it:

- **Frequency**: how many on–off cycles happen per second. The *period* is 1 / frequency.
- **Duty cycle**: the fraction of each period the signal is high, usually given as a percentage.

The average voltage is:

```
V_average = duty cycle × V_high
```

For a 3.3 V pin at 25 % duty: 0.25 × 3.3 = 0.825 V on average. At 0 % the pin is always low; at 100 % always high.

### How a timer makes PWM

A PWM timer counts from 0 up to a **top** value, then restarts. The pin is high while the count is below a **compare** value and low once it passes it. Moving the compare value changes the duty cycle; changing the clock, prescaler or top changes the frequency.

```
frequency  = clock / prescaler / (top + 1)
duty cycle ≈ compare / (top + 1)
```

The exact formula varies slightly between timer modes and chips, so the datasheet has the final word. This portable C program does the arithmetic; it runs on any computer:

```c
#include <stdio.h>

int main(void) {
    const double clock_hz = 16000000.0;  /* 16 MHz system clock */
    const int prescaler = 64;            /* timer ticks once every 64 clocks */
    const int top = 255;                 /* counter runs 0, 1, ... 255, 0, ... */

    double tick_hz = clock_hz / prescaler;
    double pwm_hz = tick_hz / (top + 1);

    int duty_percent = 25;
    int compare = (top + 1) * duty_percent / 100;
    double average_v = 3.3 * compare / (top + 1);

    printf("Timer tick: %.0f Hz\n", tick_hz);
    printf("PWM frequency: %.1f Hz\n", pwm_hz);
    printf("Compare value for %d%% duty: %d\n", duty_percent, compare);
    printf("Average of a 3.3 V signal: %.3f V\n", average_v);
    return 0;
}
```

Output:

```
Timer tick: 250000 Hz
PWM frequency: 976.6 Hz
Compare value for 25% duty: 64
Average of a 3.3 V signal: 0.825 V
```

With top = 255, there are 256 possible compare values, so this PWM has **8-bit resolution**: the duty cycle moves in steps of 1/256, about 0.4 %.

### Dimming an LED

At around 1 kHz, the LED flickers far too fast for most people to see, and it simply looks dimmer. Fading is just a loop that slowly changes the duty cycle. Using **illustrative** functions that stand in for your board's library:

```c
/* Illustrative only: pwm_start, pwm_set_duty and delay_ms stand in for
   your board's library. Duty is in parts per thousand: 250 = 25.0 %. */
#define LED_PIN 9

int main(void) {
    pwm_start(LED_PIN, 1000);                  /* 1 kHz PWM */
    while (1) {
        for (uint32_t d = 0; d <= 1000; d += 10) {
            pwm_set_duty(LED_PIN, d);          /* fade up */
            delay_ms(10);
        }
        for (uint32_t d = 1000; d > 0; d -= 10) {
            pwm_set_duty(LED_PIN, d);          /* fade down */
            delay_ms(10);
        }
    }
}
```

One subtlety: our eyes do not respond to brightness linearly. Going from 10 % to 20 % duty looks like a much bigger jump than going from 80 % to 90 %. Smooth-looking fades often use a curve (sometimes called *gamma correction*) rather than equal steps.

### Controlling motor speed

A DC motor's coil and spinning mass smooth out PWM in the same way, so its speed follows the average voltage, roughly speaking. Crucially, the GPIO pin never powers the motor. The PWM signal goes to a **motor driver**, such as a transistor or an H-bridge chip, which switches the motor's own supply on and off at the same duty cycle. The pin provides only the timing.

Frequency matters for motors. In the audible range, a few hundred hertz to a few kilohertz, motors often whine. Drivers are frequently run at around 20 kHz, near the upper limit of human hearing, so the noise disappears, though very high frequencies increase switching losses in the driver. As always, follow the driver's datasheet.

Hobby servos use PWM differently: they expect a pulse roughly every 20 ms (50 Hz), and the *width* of the pulse, typically about 1 to 2 ms, sets the angle rather than the speed.

### Recap

A timer is a hardware counter fed by a prescaled clock; overflow and compare-match events let it mark precise intervals without the CPU's help. PWM switches a pin rapidly, and its duty cycle sets the average voltage: V_average = duty × V_high. Frequency = clock / prescaler / (top + 1), and the number of compare steps sets the resolution. PWM dims LEDs and, through a driver, controls motor speed.

#### Project: Design two PWM signals on paper

Using frequency = clock / prescaler / (top + 1) and a 16 MHz clock:

1. **LED dimmer.** Choose a prescaler from 1, 8, 64, 256 or 1024, and a top value no greater than 255, that gives a frequency between 200 Hz and 2 kHz. Work out the compare value for 40 % duty and the average voltage on a 3.3 V pin.
2. **Motor driver.** Find a prescaler and top value that give a frequency within 5 % of 20 kHz. How many distinct duty-cycle steps does your choice allow? Explain the trade-off between frequency and resolution.
3. Optional: modify the C program in this lesson to check your answers.

This activity is calculation only. If you later try it on a real board, follow the safety text.

**Deliverables**

- Prescaler, top value, frequency, compare value and average voltage for the LED dimmer
- Prescaler, top value, frequency and number of duty steps for the motor signal
- Two or three sentences explaining the frequency–resolution trade-off

**Safety (adult supervision required):** Any real-hardware follow-up must be done with adult supervision, using a USB-powered board at 5 V or less. Drive LEDs through a series resistor, and drive any motor only through a proper motor driver with its own low-voltage supply, never directly from a pin. Keep fingers clear of moving parts and disconnect power before changing wiring.

#### Check your understanding

1. A 5 V PWM signal has a duty cycle of 60 %. What is its average voltage?
   A) 0.6 V
   B) 2.0 V
   C) 3.0 V
   D) 5.0 V

2. What does a timer's prescaler do?
   A) It divides the clock so the counter ticks more slowly, extending its range
   B) It sets the PWM duty cycle
   C) It stops the CPU while the timer runs
   D) It converts analog voltages to numbers

3. A timer with a 16 MHz clock, a prescaler of 8 and a top value of 99 produces PWM at what frequency?
   A) 2 kHz
   B) 200 kHz
   C) 160 kHz
   D) 20 kHz

4. Why do many motor drivers use a PWM frequency around 20 kHz?
   A) Motors only work above 20 kHz
   B) It is near the upper limit of human hearing, so the motor's whine becomes inaudible
   C) It gives the finest possible duty-cycle resolution
   D) Lower frequencies cannot change speed

**Go further:**

- Pulse-width modulation (Wikipedia): https://en.wikipedia.org/wiki/Pulse-width_modulation — Duty cycle, frequency choice and applications from LEDs to motor drives.


## 2.5 Interrupts and event-driven code

*How interrupts let a microcontroller react to events the moment they happen, why handlers must be short, and how volatile and critical sections keep shared variables safe.* (about 30 min)

### Don't miss the moment

A wheel encoder on a mobile robot produces a pulse every time the wheel turns a small fraction of a revolution. At speed, pulses can arrive thousands of times per second, and missing even a few means the robot loses track of how far it has travelled. Meanwhile, the main program is busy computing, talking to other chips and updating motors. How can it catch every pulse without staring at the pin continuously? The answer is the **interrupt**.

### Polling versus interrupts

There are two ways to notice an event.

**Polling** means checking repeatedly: "is the pin low yet? Is it low yet?" It is simple and perfectly fine when the loop is fast and events are slow. But if the loop sometimes takes 20 ms and a pulse lasts 1 ms, you will miss pulses.

**Interrupts** reverse the arrangement. You tell the hardware, "when this pin goes from high to low, interrupt me." The CPU carries on with normal work, and when the event happens, the hardware forces it to pause and run a special function, the **interrupt service routine (ISR)** or **handler**. Think of waiting for a parcel: polling is opening the front door every minute; an interrupt is a doorbell.

Many peripherals can raise interrupts: a pin changing level, a timer reaching its compare value, a byte arriving over a serial link, or an analog-to-digital conversion finishing.

### What happens when an interrupt fires

1. The event sets a flag inside the peripheral.
2. If that interrupt is enabled, the CPU finishes its current instruction.
3. It saves enough of its state (where it was in the program and some registers) to resume later.
4. It looks up the handler's address in the **vector table**, a list in flash with one entry per interrupt source.
5. It runs the handler.
6. When the handler returns, the CPU restores its saved state and carries on exactly where it left off. The main program never notices, except that time has passed.

The delay between the event and the start of the handler is the **interrupt latency**, typically a handful to a few dozen clock cycles plus any time spent waiting for another handler to finish. Chips usually let you give interrupts **priorities**, so an urgent one can be handled first.

### Rule one: keep handlers short

While a handler runs, the main program is frozen, and often other interrupts must wait too. A slow handler delays everything. So handlers should do the minimum: record that something happened, grab a timestamp, copy a received byte into a buffer, increment a counter. Then return.

Never put a `delay_ms`, a long calculation or a print statement inside a handler. Printing over a serial link can take milliseconds, during which further events may be lost. The common pattern is: **the handler sets a flag; the main loop sees the flag and does the slow work.**

### Rule two: mark shared variables volatile

Here is a subtle bug. The handler sets a variable `press_flag = 1`. The main loop checks `if (press_flag)` over and over. An optimising compiler, looking only at the main loop, sees that nothing *in the loop* changes `press_flag`. It may load the value into a CPU register once and keep checking the register, never reading memory again. The handler's change is invisible and the loop never responds.

The keyword `volatile` tells the compiler: "this variable can change in ways you cannot see; read and write the real memory every time." Every variable shared between a handler and the main program should be `volatile`. Hardware registers are declared `volatile` for the same reason.

### Rule three: protect multi-byte data

`volatile` is necessary, but not sufficient. On an 8-bit microcontroller, reading a 32-bit counter takes several instructions, one byte at a time. If the interrupt fires halfway through, you can read a value that never existed.

### Worked example: a torn read

A 16-bit counter on an 8-bit chip holds 255, which is 0x00FF in hexadecimal: high byte 0x00, low byte 0xFF.

1. The main program reads the low byte: 0xFF.
2. An interrupt fires and increments the counter to 256, which is 0x0100.
3. The main program reads the high byte: 0x01.

It combines them into 0x01FF, which is **511**. The true value was 255 a moment ago and 256 now; 511 was never correct. This kind of bug is rare, perhaps one read in thousands, which makes it maddening to track down.

The fix is a **critical section**: briefly disable interrupts, copy the value, re-enable them. Any interrupt that arrives in that window waits a few cycles and then runs normally.

### Putting it together

The code below is **illustrative**: `attach_pin_interrupt`, `interrupts_disable`, `interrupts_enable`, `gpio_set_mode` and `handle_press` stand in for your board's library and your own code. Real libraries name these differently, but the shape is the same.

```c
/* Illustrative only: these functions stand in for your board's library. */
#define BUTTON_PIN 2

volatile uint8_t  press_flag = 0;   /* set by the handler, cleared by main */
volatile uint32_t press_count = 0;  /* 32 bits: may take several instructions to read */

void on_button_falling(void) {      /* the interrupt handler: short and quick */
    press_count++;
    press_flag = 1;
}

int main(void) {
    gpio_set_mode(BUTTON_PIN, GPIO_INPUT_PULLUP);
    attach_pin_interrupt(BUTTON_PIN, EDGE_FALLING, on_button_falling);

    while (1) {
        if (press_flag) {
            interrupts_disable();       /* start of critical section */
            press_flag = 0;
            uint32_t n = press_count;   /* copy safely, all 4 bytes at once */
            interrupts_enable();        /* end of critical section */

            handle_press(n);            /* slow work happens here, not in the handler */
        }
    }
}
```

Notice how all three rules appear: the handler is two lines long, both shared variables are `volatile`, and the main loop copies the multi-byte counter inside a critical section. Keep critical sections as short as the handlers themselves, because while interrupts are off, nothing else can respond.

One warning connects to the previous lesson: a bouncing button generates several edges per press, so an interrupt on a raw button pin fires several times. Debounce in hardware, or use the interrupt only to wake the main loop and debounce there.

### Recap

Interrupts let hardware events pause the main program and run a handler, so nothing is missed while the CPU is busy. Keep handlers short: set a flag, record data, return. Declare every shared variable `volatile` so the compiler always reads real memory. Protect multi-byte shared data with a brief critical section, because `volatile` does not make a read happen all at once.

#### Project: Paper trace: find the lost update

Draw a timeline with two rows, **main** and **handler**. The handler does `count = count + 1`. The main program does `count = count - 5` (it has just processed five events). On this chip, each of those lines compiles into three steps: *load* count into a register, *change* the register, *store* it back.

1. Start with count = 10. Trace the case where the handler fires *between* main's load and main's store. What is the final value? What should it be?
2. Find a second interleaving that gives a different wrong answer, or explain why there is none.
3. Rewrite main's line using a critical section, and show on your timeline that the problem disappears.

No hardware is needed for this activity.

**Deliverables**

- A labelled two-row timeline for the faulty interleaving and its final value
- Your answer to question 2 with reasoning
- The corrected code and a timeline showing it working

#### Check your understanding

1. Which of these belongs inside an interrupt handler?
   A) A 100 ms delay so the button can settle
   B) Printing a long message over the serial port
   C) Setting a flag and incrementing a counter
   D) Recalculating the robot's whole path

2. Why must a variable shared between a handler and the main loop be declared volatile?
   A) So the compiler reads it from memory every time instead of reusing a cached copy
   B) So it is stored in flash
   C) So the interrupt fires faster
   D) So the variable can never change

3. An 8-bit chip reads a 16-bit counter one byte at a time. The counter is 0x00FF, and an interrupt increments it between reading the low and high bytes. What value is assembled?
   A) 0x00FF
   B) 0x0100
   C) 0x0000
   D) 0x01FF

4. When is simple polling a perfectly reasonable choice?
   A) When events are slow compared with how often the loop checks
   B) Never: interrupts are always better
   C) When the event lasts much less time than one pass of the loop
   D) When the variable is volatile

**Go further:**

- Interrupt (Wikipedia): https://en.wikipedia.org/wiki/Interrupt — Types of interrupts, latency, priorities and how processors handle them.
- volatile (computer programming) (Wikipedia): https://en.wikipedia.org/wiki/Volatile_(computer_programming) — What the volatile keyword does in C, and what it does not guarantee.


## 2.6 Analog-to-digital conversion

*How an ADC turns a voltage into a number: resolution, reference voltage, sampling and quantisation, and how to convert counts back into volts correctly.* (about 30 min)

### Measuring a smooth world with numbers

A gripper's force sensor, a temperature probe and a battery monitor all produce a **voltage** that varies smoothly. A microcontroller only understands numbers. The bridge between the two is the **analog-to-digital converter (ADC)**, a peripheral that measures a voltage and reports it as an integer. Almost every sensor you will read in the sensor integration module passes through an ADC, so understanding exactly what its numbers mean is essential. Most sensor bugs are really unit-conversion bugs.

### What an ADC does

An ADC compares the input voltage with a **reference voltage**, V_ref, and reports where it falls as a whole number called a **count** or **code**. An N-bit ADC has 2^N possible codes:

- 8-bit: 2^8 = 256 codes (0 to 255)
- 10-bit: 2^10 = 1,024 codes (0 to 1,023)
- 12-bit: 2^12 = 4,096 codes (0 to 4,095)

0 V gives a code of 0; a voltage at or near V_ref gives the maximum code. Everything in between is divided into equal steps.

### Resolution: the size of one step

The voltage represented by one step is called one **LSB** (least significant bit):

```
step = V_ref / 2^N
```

For a 10-bit ADC with a 3.3 V reference:

```
step = 3.3 V / 1024 ≈ 0.00322 V = 3.22 mV
```

A 12-bit ADC with the same reference has steps of 3.3 / 4096 ≈ 0.806 mV, four times finer. Any voltage within one step gives the same code, so the reading can be off by up to half a step from the true value. This unavoidable rounding is called **quantisation error**.

Be careful not to confuse *resolution* with *accuracy*. A 12-bit ADC whose reference is 2 % wrong produces very finely stepped readings that are all 2 % wrong. Real ADCs also have offset, gain and noise errors, listed in the datasheet.

### Converting counts to volts

The usual conversion is:

```
V = count × V_ref / 2^N
```

Some datasheets use 2^N − 1 instead; the difference is less than one step, but check which your chip uses.

### Worked example

A 10-bit ADC with a 3.3 V reference reads 512:

```
V = 512 × 3.3 / 1024 = 1.65 V
```

That is exactly half the reference, as you would expect for half the maximum code.

Small microcontrollers often lack fast floating-point hardware, so conversions are frequently done in whole millivolts using integers. Multiply **before** you divide, or the integer division throws away almost everything, and use a 32-bit type so the multiplication cannot overflow. (The next module explains overflow in detail.) This portable C program runs on any computer:

```c
#include <stdio.h>
#include <stdint.h>

#define ADC_BITS 10        /* counts run from 0 to 1023 */
#define VREF_MV  3300u     /* reference voltage in millivolts */

uint32_t counts_to_millivolts(uint16_t counts) {
    /* multiply first, then divide by 2^10 = 1024 */
    return ((uint32_t)counts * VREF_MV) >> ADC_BITS;
}

int main(void) {
    uint16_t samples[] = {0, 1, 230, 512, 1023};
    int n = sizeof samples / sizeof samples[0];
    for (int i = 0; i < n; i++) {
        printf("%4u counts -> %4lu mV\n", (unsigned)samples[i],
               (unsigned long)counts_to_millivolts(samples[i]));
    }
    return 0;
}
```

Output:

```
   0 counts ->    0 mV
   1 counts ->    3 mV
 230 counts ->  741 mV
 512 counts -> 1650 mV
1023 counts -> 3296 mV
```

The `>> ADC_BITS` shifts the bits right by 10 places, which divides by 1,024 and discards the remainder. That is why 1 count shows 3 mV rather than 3.22 mV. Notice too that the maximum code, 1,023, gives 3,296 mV, not 3,300: the top code represents the last step *below* V_ref.

### From volts to a physical quantity

Suppose a hypothetical temperature sensor outputs 500 mV at 0 °C and rises by 10 mV for each degree. The reading of 741 mV means:

```
temperature = (741 − 500) / 10 = 24.1 °C
```

So the chain is: counts → millivolts → physical units. Keep each step separate and labelled, and you will catch mistakes far more easily.

### The reference voltage matters

Many boards use the supply voltage as V_ref by default. If the supply sags, perhaps when a motor starts and draws a surge of current, every reading shifts with it, even though the sensor has not changed. For measurements that must be accurate, use a stable dedicated reference if the chip offers one.

Also, **never** apply a voltage above the ADC's allowed range (usually the supply) or below 0 V. To measure a larger voltage, such as a 12 V robot battery, scale it down with a voltage divider. Design for the **highest** voltage the battery can reach, not its nominal value: a "12 V" pack made of three lithium cells reaches about 12.6 V when fully charged. With R1 = 33 kΩ on top and R2 = 10 kΩ below:

```
V_out = V_in × R2 / (R1 + R2)
at 12.0 V: 12.0 × 10 / 43 ≈ 2.79 V
at 12.6 V: 12.6 × 10 / 43 ≈ 2.93 V
```

Both stay safely under 3.3 V with some margin. (A 27 kΩ top resistor would give 3.24 V at 12 V but about 3.41 V at 12.6 V, which is over the limit.) In software, multiply the measured voltage back up by 43 / 10 = 4.3.

### Sampling

An ADC does not watch the voltage continuously; it takes **samples**, snapshots at particular moments. Inside, a *sample-and-hold* circuit charges a tiny capacitor to the input voltage, disconnects it, and then measures that frozen value. Each conversion takes time, often a few to tens of microseconds, which limits the **sample rate**.

How often should you sample? Fast enough to follow the signal's real changes. A slowly changing temperature may need only a few readings per second; a vibration sensor may need thousands. Sampling too slowly can make a fast signal look like a completely different, slower one. This effect, *aliasing*, is the subject of a later lesson in the sensor integration module.

Readings also wobble by a count or two because of electrical noise. Averaging several samples is a simple, effective remedy, also covered in the sensor integration module.

### Recap

An N-bit ADC maps 0 V to V_ref onto 2^N codes, with step size V_ref / 2^N. Convert with V = count × V_ref / 2^N, multiplying before dividing and using wide enough integers. Resolution is not accuracy; the reference voltage must be stable; inputs must stay within range, scaled by a divider if necessary. Sample often enough to follow the signal, and convert counts to volts to physical units one labelled step at a time.

#### Project: Build an ADC conversion table

Using the program in this lesson as a starting point, write a C or Python program that:

1. Prints the step size in millivolts for 8-, 10- and 12-bit ADCs with a 3.3 V reference.
2. Converts a list of 10-bit readings, (0, 100, 230, 620, 1023), to millivolts, and then to temperature using the made-up sensor in this lesson (500 mV at 0 °C, 10 mV per °C).
3. Repeats step 2 assuming the reference has sagged to 3.1 V while the code still assumes 3.3 V. How many degrees of error does that cause at a reading of 230?

This is a software-only activity.

**Deliverables**

- Step sizes for the three resolutions
- A table (printed by your program) of counts, millivolts and temperature
- The temperature error caused by the sagging reference, with a sentence explaining it

#### Check your understanding

1. How many distinct codes does a 12-bit ADC have?
   A) 12
   B) 1,024
   C) 4,096
   D) 65,536

2. A 10-bit ADC with a 5.0 V reference reads 256. What is the input voltage, approximately?
   A) 1.25 V
   B) 2.56 V
   C) 0.5 V
   D) 5.0 V

3. Why does the conversion code compute counts × V_ref before dividing by 1,024?
   A) Multiplication is always faster than division
   B) Dividing first would make the result negative
   C) The ADC requires it
   D) With integers, dividing first throws away the fractional part and loses almost all precision

4. A robot's ADC readings all jump whenever its motors start, even though the sensor output has not changed. What is the most likely cause?
   A) The ADC's resolution is too high
   B) The supply voltage, used as the ADC reference, sags under the motor current
   C) Quantisation error always increases with motor speed
   D) The sample rate is exactly right

5. What is quantisation error?
   A) The rounding that occurs because every voltage within one step gives the same code
   B) Damage caused by exceeding the input range
   C) An error caused by reading the wrong pin
   D) A delay between sampling and conversion

**Go further:**

- Analog-to-digital converter (Wikipedia): https://en.wikipedia.org/wiki/Analog-to-digital_converter — Resolution, sampling, quantisation and the main ADC architectures.


---

# Module 3: Programming foundations

Writing code for devices with limited memory and no screen: the main loop, timing without blocking, and reading and setting pins.

**Objectives**

- Describe the setup-then-loop structure of typical embedded programs.
- Use variables, conditionals and loops to respond to inputs.
- Explain why blocking delays cause problems and how to schedule tasks using elapsed time.
- Debug a program using printed messages and step-by-step reasoning.


## 3.1 From source code to firmware

*What happens between typing C and a microcontroller running it: preprocessing, compiling, linking, memory sections, flashing and bootloaders.* (about 30 min)

### Text in, behaviour out

You write a few lines of C on a laptop. Minutes later, a robot's motor controller is running them, with no keyboard, screen or operating system. In between, your text passes through a chain of tools that turn it into **firmware**: the exact bytes stored in the chip's flash memory. When something goes wrong, the error message tells you *which* stage failed, and knowing the stages lets you fix problems in minutes rather than hours.

### Cross-compiling

Your laptop's processor and your microcontroller's processor usually understand completely different machine instructions. So embedded developers use a **cross-compiler**: a compiler that runs on one kind of computer and produces code for another. The ideas below are the same whether you compile for your laptop or for a chip; only the final steps differ.

### Stage 1: the preprocessor

Before compiling, the **preprocessor** handles every line beginning with `#`:

- `#include "scale.h"` pastes the contents of that file in place.
- `#define VREF_MV 3300` replaces every later `VREF_MV` with `3300`.
- `#ifdef` and friends include or skip blocks of code.

The result is one long C file with no `#` lines left. You can see it with `cc -E main.c`.

### Stage 2: the compiler

The **compiler** translates each C file on its own into an **object file** (`.o`) containing machine code. It checks syntax and types, and this is where you get errors such as a missing semicolon or an undeclared variable. With `-Wall` it also issues **warnings** about code that is legal but suspicious. Treat warnings as bugs that have not happened yet.

An object file is not yet a program. If `main.c` calls a function defined in `scale.c`, the compiler just leaves a note: "something called `counts_to_mv` goes here."

### Stage 3: the linker

The **linker** combines all the object files and libraries, fills in those notes with real addresses, and decides where everything lives in memory. For a microcontroller, a **linker script** describes the chip's memory: where flash starts, how big it is, where RAM is. If a function is called but never defined, the linker fails with an "undefined reference" or "undefined symbol" error.

### Try it on your own computer

You can practise all of this with any C compiler. Create three files.

```c
/* scale.h */
#ifndef SCALE_H
#define SCALE_H

/* Convert a 10-bit reading (0 to 1023) to millivolts for a 3300 mV reference. */
long counts_to_mv(long counts);

#endif
```

```c
/* scale.c */
#include "scale.h"

long counts_to_mv(long counts) {
    return counts * 3300 / 1024;
}
```

```c
/* main.c */
#include <stdio.h>
#include "scale.h"

int main(void) {
    long reading = 620;
    printf("%ld counts = %ld mV\n", reading, counts_to_mv(reading));
    return 0;
}
```

The `#ifndef` lines in the header are an **include guard**: they stop the header being pasted twice if several files include it. Now build each stage separately:

```
cc -std=c99 -Wall -c main.c        # compile: produces main.o
cc -std=c99 -Wall -c scale.c       # compile: produces scale.o
cc main.o scale.o -o reader        # link: produces the program
./reader
```

Output:

```
620 counts = 1998 mV
```

Now try linking without `scale.o`: `cc main.o -o broken`. Both files compiled happily, but the linker stops with an error naming `counts_to_mv` as undefined. The exact wording differs between compilers, but the meaning is the same: *declared, used, never defined*. Recognising that this is a **link** error, not a compile error, immediately tells you to look for a missing file or library rather than a typo.

### Where everything goes: memory sections

The linker sorts your program into **sections**:

- **text**: machine code and constant data. Goes in flash.
- **data**: global variables with starting values, such as `int mode = 3;`. Their starting values are stored in flash, and start-up code copies them into RAM.
- **bss**: global variables that start at zero. They take RAM, and start-up code fills them with zeros, but they need no space in flash.

The stack, which holds local variables and function return addresses, uses whatever RAM is left. Most embedded toolchains include a size tool that reports these sections. Suppose (made-up numbers for illustration) it reports text = 6,240 bytes, data = 120 bytes and bss = 880 bytes, for a chip with 32 KB of flash and 2 KB of RAM:

```
flash used = text + data = 6 240 + 120 = 6 360 bytes   (about 19 % of 32 768)
RAM used   = data + bss  = 120 + 880   = 1 000 bytes   (about 49 % of 2 048)
```

That leaves about 1 KB for the stack. Check this report every time you add a large array: running out of RAM does not give a polite error at run time; the stack quietly overwrites your variables.

### Stage 4: flashing

The linked output, often an **ELF** file containing code plus debugging information, is converted into a raw binary or a **hex** file listing bytes and addresses. Then it must get into the chip's flash. There are two common ways:

1. **A programmer or debug probe**: a small device that connects to dedicated pins on the chip and writes flash directly. It can also pause the CPU, step through code and read variables, which makes it the most powerful debugging tool you have.
2. **A bootloader**: a small program already stored in a protected part of flash. After reset, it runs first and checks whether new firmware is arriving, for example over USB or a serial port. If so, it writes the new firmware into flash; if not, it jumps to your application. Many hobby boards work this way, so you can upload over a plain USB cable.

A bootloader is convenient and enables updates in the field, but it occupies some flash, adds a short delay at start-up, and must be protected carefully: if an update is interrupted halfway, a well-designed bootloader keeps the old firmware or waits for a retry rather than leaving the device unusable.

### Recap

The preprocessor expands `#include` and `#define`; the compiler turns each C file into an object file and reports syntax and type errors; the linker joins object files, resolves names and places sections in memory according to the chip's layout. Code and constants live in flash; initialised and zeroed globals take RAM, with the stack in what remains. The result is flashed through a debug probe or a bootloader. Every error message belongs to one stage, and knowing which stage narrows the search.

> **Practise on a desktop first.** All the commands in this lesson work with a free C compiler on Windows, macOS or Linux, or in a free online C environment. You do not need a microcontroller to learn the build process: cross-compiling for a chip uses the same stages, just with different tools.

#### Project: Break the build on purpose

Create the three files from this lesson and build them stage by stage. Then cause, and record, one error from each stage:

1. **Preprocessor:** misspell the header name in `#include "scale.h"`.
2. **Compiler:** delete a semicolon in `scale.c`.
3. **Linker:** link without `scale.o`.
4. **Warning:** declare an unused variable inside `main` and compile with `-Wall`.

For each, copy the key line of the message and write one sentence saying which stage produced it and how you could tell. Finally, run `cc -E main.c` and describe what happened to the `#include` lines.

**Deliverables**

- Four recorded messages, each labelled with the stage that produced it
- One sentence per message explaining how you identified the stage
- A short description of the preprocessor output

#### Check your understanding

1. Both main.c and scale.c compile without errors, but building the program fails with "undefined reference to counts_to_mv". Which stage failed?
   A) The preprocessor
   B) The compiler
   C) The linker
   D) The bootloader

2. What is a cross-compiler?
   A) A compiler that runs on one kind of computer and produces machine code for a different kind
   B) A compiler that checks code written in two languages
   C) A tool that copies firmware into flash
   D) A compiler that only produces warnings

3. A global variable is declared as int samples[400]; with no starting value. Which section does it go in?
   A) text, in flash
   B) data, stored in flash and copied to RAM
   C) The bootloader
   D) bss, in RAM, zeroed at start-up

4. What does a bootloader do?
   A) It translates C into machine code
   B) It runs first after reset, can receive and write new firmware, and otherwise jumps to the application
   C) It converts analog voltages into numbers
   D) It checks code for warnings

**Go further:**

- Linker (computing) (Wikipedia): https://en.wikipedia.org/wiki/Linker_(computing) — How linkers combine object files and resolve symbols.
- Bootloader (Wikipedia): https://en.wikipedia.org/wiki/Bootloader — What bootloaders do in computers and embedded devices.


## 3.2 C types, sizes and integer overflow

*Why embedded C uses fixed-width types like uint8_t and int32_t, what happens when a value no longer fits, and how to write arithmetic that stays correct.* (about 30 min)

### When numbers run out of room

A robot's wheel encoder counts pulses into a variable. After a long drive, the count suddenly jumps from a large positive number to a large negative one, and the robot believes it has teleported backwards. Nothing is broken: the variable simply ran out of bits. In embedded systems, where memory is precious and variables are often small, knowing exactly how big each number is, and what happens at its limits, is basic engineering hygiene.

### The problem with int

In C, the size of `int` is not fixed by the language. The standard only promises it is at least 16 bits. On a typical laptop it is 32 bits; on many 8-bit microcontrollers it is 16 bits. Code that works on your laptop can therefore overflow on the chip.

The solution is the `<stdint.h>` header, part of C99, which provides **fixed-width types** whose size never changes:

```
type        bits   range
int8_t      8      −128 to 127
uint8_t     8      0 to 255
int16_t     16     −32 768 to 32 767
uint16_t    16     0 to 65 535
int32_t     32     −2 147 483 648 to 2 147 483 647
uint32_t    32     0 to 4 294 967 295
```

The `u` means **unsigned**: no negative numbers, so the whole range is available for positive values. An N-bit unsigned type holds 0 to 2^N − 1. A signed type uses *two's complement* and holds −2^(N−1) to 2^(N−1) − 1.

Choose types deliberately. A raw ADC reading of 0 to 1,023 fits in `uint16_t`. A count of milliseconds since power-on needs `uint32_t`. A temperature that might go below zero needs a signed type. Smaller types save RAM, which matters when you have only 2 KB.

### Unsigned overflow wraps around

When an unsigned value goes past its maximum, C defines exactly what happens: it **wraps around** to zero, like a car's mileage counter rolling over. Mathematically, the result is taken modulo 2^N. So for `uint8_t`, 255 + 1 = 0 and 250 + 10 = 260 − 256 = 4.

### Signed overflow is undefined

For **signed** types, overflow is **undefined behaviour**. The C standard places no requirement on what happens. In practice you often see wrap-around to a large negative number, as in the encoder story, but optimising compilers are allowed to assume overflow never happens and may generate code that behaves in surprising ways. The rule: never let signed arithmetic overflow. If you need wrap-around, use unsigned types, where it is guaranteed.

### Seeing it happen

This portable program runs on any computer. Compile it with `cc -std=c99 -Wall types.c -o types`.

```c
#include <stdio.h>
#include <stdint.h>

int main(void) {
    uint8_t count = 250;
    for (int i = 0; i < 10; i++) {
        count++;                       /* 250 + 10 = 260, but 8 bits hold 0..255 */
    }
    printf("count = %u\n", (unsigned)count);

    uint16_t counts = 1023, vref_mv = 3300;
    uint16_t wrong = counts * vref_mv;            /* result squeezed into 16 bits */
    uint32_t right = (uint32_t)counts * vref_mv;  /* widen first, then multiply */
    printf("wrong = %u, right = %lu\n", (unsigned)wrong, (unsigned long)right);

    int a = -1;
    unsigned int b = 1;
    printf("-1 < 1u is %s\n", (a < b) ? "true" : "false");

    printf("sizes in bytes: %zu %zu %zu\n",
           sizeof(uint8_t), sizeof(uint16_t), sizeof(uint32_t));
    return 0;
}
```

Output:

```
count = 4
wrong = 33564, right = 3375900
-1 < 1u is false
sizes in bytes: 1 2 4
```

Each line teaches something.

**Line 1.** 250 + 10 = 260, which wraps to 260 − 256 = 4.

**Line 2.** The true product 1,023 × 3,300 = 3,375,900 needs more than 16 bits. Stored in a `uint16_t`, it becomes 3,375,900 mod 65,536 = 33,564. That is a plausible-looking number, which makes the bug dangerous. Casting one operand to `uint32_t` *before* multiplying makes the whole calculation 32-bit. This is exactly why the ADC lesson's conversion function widened first.

**Line 3.** When you compare a signed and an unsigned value, C converts the signed one to unsigned. −1 becomes 4,294,967,295 (on a system with 32-bit `int`), which is not less than 1. Many compilers do not warn about this with `-Wall` alone; `-Wextra` adds the warning. Avoid mixing signed and unsigned in comparisons.

**Line 4.** `sizeof` reports sizes in bytes, confirming that fixed-width types are the same everywhere.

### Integer promotion: a hidden step

In C, arithmetic on types smaller than `int` first **promotes** them to `int` (or `unsigned int`). That is why `uint8_t` variables can be added without overflow in the middle of an expression, and only wrap when the result is stored back into a `uint8_t`. It also explains why the "wrong" product above is computed at full size and then cut down when stored. The rules are subtle; the practical advice is to make the type of every intermediate result explicit when it might be large.

### Integer division truncates

`7 / 2` in C is 3, not 3.5: integer division throws away the remainder. Combined with overflow, this gives the golden rule for scaled arithmetic: **multiply before dividing, in a type wide enough for the product**. Compute `counts * 3300 / 1024` in 32 bits, not `counts / 1024 * 3300`, which is 0 for every reading below 1,024.

### A real-world warning

On its first flight in 1996, the Ariane 5 rocket was lost about 40 seconds after launch. A key cause was a software conversion of a 64-bit floating-point number into a 16-bit signed integer: the value was too big to fit, the conversion failed, and the guidance system shut down. The code had been reused from Ariane 4, whose slower flight never produced such large values. The lesson for every embedded engineer: know the range of every variable, and check that it still holds when the system changes.

### Recap

`int` has no fixed size, so embedded C uses `<stdint.h>` types such as `uint8_t` and `int32_t`. An N-bit unsigned type holds 0 to 2^N − 1 and wraps around predictably; signed overflow is undefined and must be avoided. Widen before multiplying, multiply before dividing, avoid mixing signed and unsigned in comparisons, and know the range each variable must hold.

#### Project: Find the limits

Write a short C99 program, compiled with `cc -std=c99 -Wall -Wextra`, that:

1. Stores 65,535 in a `uint16_t`, adds 1, and prints the result. Predict the answer first.
2. Counts milliseconds in a `uint16_t`. Calculate by hand how many seconds pass before it wraps, and how many days a `uint32_t` millisecond counter lasts.
3. Computes a 12-bit ADC reading of 4,095 times a reference of 3,300 mV, first entirely in `uint16_t` and then with a `uint32_t` cast. Print both and explain the difference.
4. Fixes the signed/unsigned comparison from this lesson so it prints `true`, without changing the values.

This is a software-only activity.

**Deliverables**

- Your program and its output
- Your hand calculations for the 16-bit and 32-bit millisecond wrap times
- One or two sentences explaining each surprising result

#### Check your understanding

1. A uint8_t variable holds 200. You add 100 and store the result back in it. What does it hold?
   A) 300
   B) 255
   C) 44
   D) −56

2. Why do embedded programmers prefer int16_t or int32_t over plain int?
   A) The size of int depends on the compiler and chip, while fixed-width types are the same everywhere
   B) int cannot hold negative numbers
   C) Fixed-width types are always faster
   D) int is not part of C99

3. What does the C standard say happens when a signed int overflows?
   A) It always wraps to the most negative value
   B) It saturates at the maximum value
   C) The program always stops with an error
   D) The behaviour is undefined, so the compiler may assume it never happens

4. Which expression correctly converts a 10-bit reading counts (a uint16_t) to millivolts with a 3,300 mV reference?
   A) counts / 1024 * 3300
   B) (uint32_t)counts * 3300 / 1024
   C) (uint8_t)counts * 3300 / 1024
   D) counts * (3300 / 1024)

**Go further:**

- C data types (Wikipedia): https://en.wikipedia.org/wiki/C_data_types — Sizes, ranges and the fixed-width types from stdint.h.
- Integer overflow (Wikipedia): https://en.wikipedia.org/wiki/Integer_overflow — How overflow happens, how languages handle it, and notable failures it has caused.


## 3.3 Bitwise operations and hardware registers

*Using masks and the bitwise operators to set, clear, toggle and test individual bits, and reading a datasheet's register map to control hardware.* (about 35 min)

### One number, many switches

Inside a microcontroller, a single 8-bit control register might hold eight unrelated settings: bit 0 switches a timer on, bit 1 enables its interrupt, three more bits choose its speed. To change one setting without disturbing the others, you need to work on individual bits. C's **bitwise operators** do exactly this, and they appear in almost every piece of firmware that talks to hardware. You met binary and hexadecimal in the digital electronics module; now you will use them.

### The bitwise operators

Bitwise operators work on each bit position independently, using the logic gates you already know.

```
operator   name          example (binary)                result
&          AND           1100 & 1010                     1000
|          OR            1100 | 1010                     1110
^          XOR           1100 ^ 1010                     0110
~          NOT           ~1100  (in 4 bits)              0011
<<         shift left    0001 << 2                       0100
>>         shift right   1000 >> 3                       0001
```

Do not confuse `&` with `&&` or `|` with `||`. The doubled versions are *logical* operators that treat a whole value as true or false. `6 & 1` is 0, but `6 && 1` is 1.

### Masks

A **mask** is a number with 1s in exactly the bit positions you care about. The easiest way to make a mask for bit n is to shift a 1 into place:

```
1u << 0   = 0000 0001   (bit 0)
1u << 3   = 0000 1000   (bit 3)
1u << 7   = 1000 0000   (bit 7)
```

The `u` makes the 1 unsigned, which avoids undefined behaviour when shifting into the top bit of a signed value.

### The four essential moves

With a register value `reg` and a mask `m`:

- **Set** the bits in m (make them 1): `reg |= m;` OR with 1 forces a 1; OR with 0 leaves a bit alone.
- **Clear** the bits in m (make them 0): `reg &= ~m;` `~m` has 0s only where m has 1s, and AND with 0 forces a 0.
- **Toggle** the bits in m: `reg ^= m;` XOR with 1 flips a bit; XOR with 0 leaves it.
- **Test** whether a bit is set: `if (reg & m)`. The result is non-zero only if that bit is 1.

These are **read-modify-write** operations: read the whole register, change some bits, write the whole value back.

### Multi-bit fields

Some settings take several bits. Suppose bits 4 to 6 hold a 3-bit *prescaler* field with values 0 to 7. To read it, mask and shift down. To write it, clear the field, then OR in the new value shifted into place:

```
field_mask = 0x7u << 4                         (0111 0000)
read:   value = (reg & field_mask) >> 4
write:  reg = (reg & ~field_mask) | ((new_value << 4) & field_mask)
```

The final `& field_mask` stops an oversized `new_value` from spilling into neighbouring bits.

### Reading a register map

Datasheets describe each register with a bit-by-bit map. Here is a **made-up** control register for a fictional timer, written the way datasheets usually present them:

```
TIMER_CTRL (8 bits, read/write, value after reset: 0x00)

bit 7      reserved     always write 0
bits 6..4  PRESCALE     clock divider select, 0 to 7
bit 3..2   reserved     always write 0
bit 1      IRQ_EN       1 = interrupt on overflow
bit 0      EN           1 = timer running
```

From this, the code names follow naturally. Using named constants rather than raw numbers like `0x53` makes code readable and much easier to check against the datasheet.

```c
#include <stdio.h>
#include <stdint.h>

#define CTRL_EN              (1u << 0)
#define CTRL_IRQ_EN          (1u << 1)
#define CTRL_PRESCALE_SHIFT  4
#define CTRL_PRESCALE_MASK   (0x7u << CTRL_PRESCALE_SHIFT)

int main(void) {
    uint8_t ctrl = 0x00;   /* a plain variable standing in for the register */

    ctrl |= CTRL_EN;                                  /* set bit 0 */
    printf("enable:      0x%02X\n", (unsigned)ctrl);

    ctrl |= CTRL_IRQ_EN;                              /* set bit 1 */
    printf("irq on:      0x%02X\n", (unsigned)ctrl);

    /* write 5 into the 3-bit PRESCALE field, leaving other bits alone */
    ctrl = (ctrl & ~CTRL_PRESCALE_MASK)
         | ((5u << CTRL_PRESCALE_SHIFT) & CTRL_PRESCALE_MASK);
    printf("prescale=5:  0x%02X\n", (unsigned)ctrl);

    ctrl &= ~CTRL_IRQ_EN;                             /* clear bit 1 */
    printf("irq off:     0x%02X\n", (unsigned)ctrl);

    ctrl ^= CTRL_EN;                                  /* toggle bit 0 */
    printf("toggle en:   0x%02X\n", (unsigned)ctrl);

    unsigned prescale = (ctrl & CTRL_PRESCALE_MASK) >> CTRL_PRESCALE_SHIFT;
    printf("prescale field reads %u, enabled: %s\n", prescale,
           (ctrl & CTRL_EN) ? "yes" : "no");
    return 0;
}
```

This is portable C: it runs on any computer, using a variable in place of the hardware. Output:

```
enable:      0x01
irq on:      0x03
prescale=5:  0x53
irq off:     0x51
toggle en:   0x50
prescale field reads 5, enabled: no
```

Check 0x53 by hand: in binary it is 0101 0011. Bits 6 to 4 are 101, which is 5; bit 1 and bit 0 are both 1. Exactly what we asked for.

### From a variable to real hardware

On a real chip, the register lives at a fixed memory address given in the datasheet. Firmware reaches it through a pointer marked `volatile`, so the compiler performs every read and write exactly as written:

```c
/* Illustrative pattern only. TIMER_CTRL_ADDRESS must come from your chip's
   datasheet or the manufacturer's header file; no real address is shown here. */
#define TIMER_CTRL (*(volatile uint8_t *)TIMER_CTRL_ADDRESS)

void timer_enable(void) {
    TIMER_CTRL |= CTRL_EN;   /* read the register, set bit 0, write it back */
}
```

In practice, manufacturers supply header files that define every register and bit name, so you rarely type an address yourself. But knowing what those definitions do lets you read them, check them against the datasheet and debug them.

Two cautions. First, some register bits behave unusually: a datasheet may say a status bit is *cleared by writing 1*, or that a register is read-only. A read-modify-write on such a register can have side effects, so read the description of every bit you touch. Second, a read-modify-write takes several instructions. If an interrupt handler modifies the same register in the middle, one change can be lost, the same problem as the shared-variable race in the interrupts lesson.

### Recap

Bitwise operators work on each bit separately. A mask such as `1u << n` selects bits. Set with `|=`, clear with `&= ~`, toggle with `^=`, test with `&`. Multi-bit fields are read by masking and shifting down, and written by clearing the field and ORing in the shifted value. Datasheet register maps tell you which bits mean what; give them names in code, access real registers through `volatile` pointers, and read every bit's description before you write to it.

#### Project: Decode and encode a register by hand

Use the made-up TIMER_CTRL register from this lesson.

1. Decode these values by hand, stating PRESCALE, IRQ_EN and EN for each: 0x00, 0x31, 0x72, 0x7F. Which one breaks the datasheet's "always write 0" rule for the reserved bits?
2. Starting from 0x51, write the single C statement that sets PRESCALE to 2 without changing any other bit. What is the new value in hex?
3. Extend the program in this lesson with a function `void set_prescale(uint8_t *reg, unsigned value)` and test it with values 0, 7 and 9. What does your function do with 9, and is that what you want?

Check your hand answers by running the program.

**Deliverables**

- A decoded breakdown of the four values, with the rule-breaking value identified
- Your C statement and the resulting hex value
- The set_prescale function, its test output and a sentence on handling 9

#### Check your understanding

1. reg holds 0x0F. What is reg after reg &= ~(1u << 2)?
   A) 0x0B
   B) 0x04
   C) 0x0F
   D) 0x1F

2. Which statement toggles bit 5 of reg and leaves the other bits unchanged?
   A) reg |= (1u << 5);
   B) reg = (1u << 5);
   C) reg &= (1u << 5);
   D) reg ^= (1u << 5);

3. A register reads 0x53. Its PRESCALE field occupies bits 6 to 4. What value does PRESCALE hold?
   A) 3
   B) 5
   C) 53
   D) 6

4. Why are hardware registers accessed through volatile pointers?
   A) To make them faster
   B) So that they are stored in flash
   C) So the compiler performs every read and write exactly as written, because the hardware can change or react to them
   D) Because volatile is required for all pointers in C

5. What is the difference between 6 & 1 and 6 && 1 in C?
   A) 6 & 1 is 0 (bitwise AND of 110 and 001); 6 && 1 is 1 (both values are non-zero, so logically true)
   B) There is no difference
   C) 6 & 1 is 1 and 6 && 1 is 0
   D) Both are errors

**Go further:**

- Bitwise operations in C (Wikipedia): https://en.wikipedia.org/wiki/Bitwise_operations_in_C — Each operator with worked examples, and the difference from logical operators.
- Mask (computing) (Wikipedia): https://en.wikipedia.org/wiki/Mask_(computing) — Common masking patterns for setting, clearing and testing bits.


## 3.4 Super-loops and finite state machines

*How most firmware is structured as a loop that runs forever, and how a finite state machine keeps complicated behaviour clear, testable and safe.* (about 30 min)

### Structure before features

A robot gripper must close when asked, stop when it is holding firmly, release on command, and refuse to keep squeezing if something goes wrong. Written as a pile of `if` statements and flags, this logic quickly becomes a tangle that nobody, including its author, can reason about. Two simple structures, the **super-loop** and the **finite state machine**, keep firmware understandable as it grows. They are used in a huge range of real embedded products.

### The super-loop

Most bare-metal firmware has the same shape: set things up once, then loop forever.

```c
/* Illustrative structure: the four functions are your own code. */
int main(void) {
    setup_hardware();        /* runs once after reset */
    while (1) {              /* runs forever */
        read_inputs();       /* sample buttons, sensors, messages */
        update_logic();      /* decide what to do */
        write_outputs();     /* drive LEDs, motors, displays */
    }
}
```

This is the **super-loop**. It is the sense–think–act loop from robotics foundations, written in C. Its strengths are simplicity and predictability: there is no operating system, and you can see everything the chip does. Its main rule is that **nothing inside the loop may take long**, because while one part is busy, every other part waits. The next lesson shows how to wait without blocking.

Separating the three phases also helps. If `update_logic` works only with values that `read_inputs` has stored, and produces values that `write_outputs` applies, the logic can be tested on a laptop with made-up inputs, no hardware needed.

### Why flags get messy

Imagine writing the gripper logic with flags: `is_closing`, `is_holding`, `is_opening`, `has_fault`. Four true/false flags allow 2^4 = 16 combinations. Most are meaningless: closing *and* opening at once? Holding *and* faulted? Each one is a bug waiting to happen. What we really mean is that the gripper is in exactly *one* situation at a time.

### Finite state machines

A **finite state machine (FSM)** has:

- a fixed list of **states**, of which exactly one is current;
- **inputs** or **events** that the machine responds to;
- **transitions**: rules saying which event moves it from one state to another;
- **actions**: what the outputs do in each state or on each transition.

Here is the gripper as a state machine, written as a list of transitions:

```
IDLE     --close command-->        CLOSING
CLOSING  --force reached-->        HOLDING
CLOSING  --2 s without force-->    FAULT
HOLDING  --open command-->         OPENING
OPENING  --fully open switch-->    IDLE
FAULT    (stays until a person resets the system)
```

Drawing this as circles and arrows on paper before writing code is one of the best habits you can build. Every arrow should have a label; every state should say what happens to unexpected events.

The **timeout** from CLOSING to FAULT is a safety feature. If the object slips out or a sensor fails, the gripper must not squeeze forever. State machines make such rules explicit and easy to review.

### Writing it in C

An `enum` names the states and a `switch` statement handles each one. The decision logic is a **pure function**: it takes the current state and inputs, returns the next state, and touches no hardware. This portable program simulates it with a made-up script of inputs, one step every 100 ms:

```c
#include <stdio.h>

typedef enum { IDLE, CLOSING, HOLDING, OPENING, FAULT } State;
static const char *state_name[] = { "IDLE", "CLOSING", "HOLDING", "OPENING", "FAULT" };

typedef struct {
    int close_cmd;    /* 1 = asked to grip */
    int open_cmd;     /* 1 = asked to release */
    int force_ok;     /* 1 = grip force has reached its target */
    int fully_open;   /* 1 = jaws are at the open limit switch */
} Inputs;

#define CLOSE_TIMEOUT_MS 2000

/* Pure function: current state + inputs + time in state -> next state. */
State next_state(State s, const Inputs *in, int ms_in_state) {
    switch (s) {
    case IDLE:
        return in->close_cmd ? CLOSING : IDLE;
    case CLOSING:
        if (in->force_ok) return HOLDING;
        if (ms_in_state >= CLOSE_TIMEOUT_MS) return FAULT;
        return CLOSING;
    case HOLDING:
        return in->open_cmd ? OPENING : HOLDING;
    case OPENING:
        return in->fully_open ? IDLE : OPENING;
    case FAULT:
        return FAULT;   /* stays here until a person resets the system */
    }
    return FAULT;       /* unknown state: fail safe */
}

int main(void) {
    State s = IDLE;
    int ms_in_state = 0;

    /* Made-up test script, one step every 100 ms. */
    for (int t = 0; t <= 5000; t += 100) {
        Inputs in = {0, 0, 0, 0};
        if (t == 300 || t == 2200) in.close_cmd = 1;
        if (t >= 900 && t < 1500)  in.force_ok = 1;
        if (t == 1500)             in.open_cmd = 1;
        if (t >= 1900 && t < 2100) in.fully_open = 1;

        State n = next_state(s, &in, ms_in_state);
        if (n != s) {
            printf("t=%4d ms  %-7s -> %s\n", t, state_name[s], state_name[n]);
            s = n;
            ms_in_state = 0;
        } else {
            ms_in_state += 100;
        }
    }
    return 0;
}
```

Output:

```
t= 300 ms  IDLE    -> CLOSING
t= 900 ms  CLOSING -> HOLDING
t=1500 ms  HOLDING -> OPENING
t=1900 ms  OPENING -> IDLE
t=2200 ms  IDLE    -> CLOSING
t=4300 ms  CLOSING -> FAULT
```

The first cycle works normally. In the second, the force sensor never reports success, so the timeout fires and the gripper enters FAULT. (It fires at 4,300 ms rather than 4,200 ms because this simple counter starts at zero on entry and is only checked once per 100 ms step. Off-by-one-step details like this are exactly what desktop tests reveal.)

### Good habits for state machines

- **One variable holds the state.** No separate flags that can disagree.
- **Every state handles every input**, even if the answer is "stay here". The `return FAULT` after the `switch` catches a corrupted or unknown state and fails safe.
- **Outputs follow from the state.** In `write_outputs`, the motor runs forward only in CLOSING, backward only in OPENING, and is off in every other state. Then the outputs can never contradict the state.
- **Test on a desktop first.** Because `next_state` touches no hardware, you can run hundreds of scripted scenarios, including rare faults, before the code ever moves a real motor.

### Recap

Most firmware is a super-loop: set up once, then repeatedly read inputs, update logic and write outputs, with nothing inside allowed to take long. A finite state machine replaces tangled flags with one current state, clear transitions and explicit actions. Write the transition logic as a pure function using `enum` and `switch`, include a fail-safe default and timeouts, and test it with scripted inputs before it touches hardware.

#### Project: Design a state machine for a robot charging dock

A small mobile robot drives back to a charging dock when its stored charge is low. Design the firmware's state machine.

1. On paper, draw states such as WORKING, RETURNING, DOCKING, CHARGING and FAULT, with labelled arrows for events like "charge below 20 %", "dock in sight", "contacts touching", "fully charged" and timeouts.
2. Decide what happens if the dock is not found within 60 seconds.
3. Write `next_state` in C99 using an `enum` and `switch`, adapting the gripper example.
4. Write a scripted test in `main` with made-up inputs that exercises at least one normal charge cycle and one fault, and print every transition.

This is a paper and software activity; no hardware is needed.

**Deliverables**

- A labelled state diagram with every transition named
- Your next_state function, compiled with cc -std=c99 -Wall without warnings
- Printed transitions from your scripted test, covering a normal cycle and a fault

#### Check your understanding

1. What is the most important rule for code inside a super-loop?
   A) It must use interrupts for everything
   B) Each part must finish quickly, because while one part runs every other part waits
   C) It must never read inputs
   D) It must return from main after each pass

2. Why is a single state variable better than four separate true/false flags for the gripper?
   A) Flags use more flash memory
   B) C does not support booleans
   C) Four flags allow 16 combinations, most meaningless, while one state variable allows exactly one valid situation at a time
   D) State variables are faster to read

3. In the gripper machine, what is the purpose of the CLOSING-to-FAULT timeout?
   A) To stop the gripper squeezing forever if the force target is never reached, for example because the object slipped or a sensor failed
   B) To save battery during HOLDING
   C) To make the gripper close faster
   D) To debounce the close command

4. Why is next_state written as a pure function that touches no hardware?
   A) Hardware access is not allowed inside switch statements
   B) Pure functions use less RAM
   C) It makes the code run faster on the microcontroller
   D) It can be tested on a desktop computer with scripted inputs, including rare faults, before running on real hardware

**Go further:**

- Finite-state machine (Wikipedia): https://en.wikipedia.org/wiki/Finite-state_machine — The theory of state machines, state diagrams and their many applications.


## 3.5 Non-blocking timing and timer wrap-around

*Why delay functions freeze the whole program, how to schedule several tasks by checking elapsed time, and how unsigned arithmetic handles timer wrap-around correctly.* (about 30 min)

### The problem with waiting

A robot needs to blink a status light every half second, read its distance sensor every 10 ms and check its emergency-stop button constantly. The beginner's blink program from the GPIO lesson used `delay_ms(500)`. During that half second the CPU does nothing else: it reads no sensors and **does not notice the stop button**. One blocking delay can make the whole robot deaf. This lesson replaces waiting with *checking the time*, the single most useful pattern in super-loop firmware.

### Blocking versus non-blocking

A **blocking** call does not return until its job is finished. `delay_ms(500)` is the extreme case: it spends 500 ms counting.

A **non-blocking** approach asks, on every pass of the loop, "has enough time passed yet?" If yes, it does the job and notes the time. If no, it moves on immediately. Each check takes microseconds, so the loop keeps spinning and every task gets attention.

To ask that question you need a clock. Most firmware keeps a counter of milliseconds since power-on, incremented by a timer interrupt every 1 ms, as built in the timers lesson. We will call it `millis_now()`, an **illustrative** name for whatever your board's library provides. It returns a `uint32_t`.

### The elapsed-time pattern

```c
/* Illustrative only: millis_now, gpio_set_mode, gpio_write and gpio_read
   stand in for your board's library; handle_press is your own code. */
#define LED_PIN    13
#define BUTTON_PIN 2

int main(void) {
    gpio_set_mode(LED_PIN, GPIO_OUTPUT);
    gpio_set_mode(BUTTON_PIN, GPIO_INPUT_PULLUP);
    uint32_t last_blink = millis_now();
    int led = 0;

    while (1) {
        uint32_t now = millis_now();

        if ((uint32_t)(now - last_blink) >= 500) {   /* is it time yet? */
            last_blink += 500;
            led = !led;
            gpio_write(LED_PIN, led);
        }

        if (gpio_read(BUTTON_PIN) == 0) {             /* checked every pass */
            handle_press(now);
        }
    }
}
```

The LED still blinks every 500 ms, but the button is now checked thousands of times per second. (In real code you would debounce it, as in the microcontrollers module.)

Notice `last_blink += 500` rather than `last_blink = now`. If the loop happens to notice 3 ms late, `= now` would push every later blink 3 ms later, and small delays would add up into **drift**. Adding the interval keeps the schedule locked to the original timeline. The trade-off: if the loop were ever stalled for several intervals, `+=` would run the task several times in quick succession to catch up. For blinking that is harmless; for some tasks, `= now` is the better choice. Decide deliberately.

### Several tasks, one loop

Each task gets its own "last run" variable. This portable program simulates two seconds of a loop with a pretend clock that advances 1 ms per pass:

```c
#include <stdio.h>
#include <stdint.h>

int main(void) {
    uint32_t last_blink = 0, last_sensor = 0;
    int led = 0, blinks = 0, sensor_reads = 0;

    /* Pretend clock: one pass of the loop per millisecond for 2 seconds. */
    for (uint32_t now = 0; now < 2000; now++) {
        if ((uint32_t)(now - last_sensor) >= 10) {   /* every 10 ms */
            last_sensor += 10;
            sensor_reads++;
        }
        if ((uint32_t)(now - last_blink) >= 500) {   /* every 500 ms */
            last_blink += 500;
            led = !led;
            blinks++;
        }
    }
    printf("sensor reads: %d, LED toggles: %d, LED now %s\n",
           sensor_reads, blinks, led ? "on" : "off");
    return 0;
}
```

Output:

```
sensor reads: 199, LED toggles: 3, LED now on
```

Why 199 and not 200? The first read happens at 10 ms, not at 0, and the simulation stops at 1,999 ms, so reads occur at 10, 20, ..., 1,990 ms: 199 of them. Toggles happen at 500, 1,000 and 1,500 ms. Counting exactly like this is how you check timing code.

### Wrap-around

A `uint32_t` holds up to 4,294,967,295. Counting milliseconds, it reaches that after:

```
4 294 967 296 ms ÷ 1000 ÷ 60 ÷ 60 ÷ 24 ≈ 49.7 days
```

Then it wraps around to 0, as you saw in the C types lesson. A robot left running for seven weeks will hit this. A 16-bit tick counter wraps after only 65.536 seconds. Code that mishandles the wrap usually passes every test on the bench, then fails in the field.

The good news: **unsigned subtraction handles wrap-around automatically.** Because unsigned arithmetic works modulo 2^32, `now - last` gives the true elapsed time even when `now` has wrapped past zero. The tempting alternative, `now >= last + interval`, does not. This portable program compares both, with `last` set 296 ms before the wrap:

```c
#include <stdio.h>
#include <stdint.h>

/* Correct: unsigned subtraction gives elapsed time even across a wrap. */
int is_due_good(uint32_t now, uint32_t last, uint32_t interval) {
    return (uint32_t)(now - last) >= interval;
}

/* Wrong: last + interval can wrap to a small number. */
int is_due_bad(uint32_t now, uint32_t last, uint32_t interval) {
    return now >= last + interval;
}

int main(void) {
    uint32_t last = 4294967000u;     /* 296 ms before the counter wraps */
    uint32_t interval = 500;
    uint32_t times[] = {4294967100u, 4294967295u, 0u, 200u, 204u};
    int n = sizeof times / sizeof times[0];

    for (int i = 0; i < n; i++) {
        uint32_t now = times[i];
        printf("now=%10lu  elapsed=%3lu  good=%d  bad=%d\n",
               (unsigned long)now, (unsigned long)(uint32_t)(now - last),
               is_due_good(now, last, interval), is_due_bad(now, last, interval));
    }
    return 0;
}
```

Output:

```
now=4294967100  elapsed=100  good=0  bad=1
now=4294967295  elapsed=295  good=0  bad=1
now=         0  elapsed=296  good=0  bad=0
now=       200  elapsed=496  good=0  bad=0
now=       204  elapsed=500  good=1  bad=1
```

`last + interval` = 4,294,967,500, which wraps to 204. So the bad version thinks the task is due when only 100 ms have passed: any huge `now` is "greater than 204". The good version reports due exactly when 500 ms have elapsed, straight across the wrap. Casting the difference back to the counter's own type matters for smaller types: `uint16_t` values are promoted to `int` before subtracting, so without a `(uint16_t)` cast the difference can come out negative.

### Recap

Blocking delays freeze everything, so super-loop firmware checks the time instead: `if ((uint32_t)(now - last) >= interval)`, then advance `last`. Give each task its own timestamp, use `last += interval` to avoid drift, and count expected runs to verify your code. Timer counters wrap (a 32-bit millisecond counter after about 49.7 days), and unsigned subtraction gives the correct elapsed time across the wrap, while comparing against `last + interval` does not.

#### Project: Three tasks and a wrap test

Extend the two-task simulation in this lesson:

1. Add a third task that "prints a status report" every 1,000 ms. Predict how many times each task runs in 5 seconds, then run it and compare.
2. Start the pretend clock at 4,294,965,000 instead of 0 and run for 5,000 passes, so the counter wraps during the run. Confirm the counts are unchanged.
3. Change one task to the wrong test, `now >= last + interval`, and repeat step 2. Describe what goes wrong.
4. Repeat the wrap test using `uint16_t` for the clock and timestamps, with and without the `(uint16_t)` cast on the subtraction. Explain any difference.

This is a software-only activity.

**Deliverables**

- Predicted and actual run counts for all three tasks
- Output showing correct behaviour across the wrap with the good test
- Output and explanation for the wrong test and for the 16-bit experiment

#### Check your understanding

1. A super-loop blinks an LED with delay_ms(1000) and also checks a stop button. What is the problem?
   A) The LED will blink too fast
   B) delay_ms uses too much RAM
   C) During each delay the button is not checked, so a press can be missed or noticed up to a second late
   D) There is no problem

2. Roughly how long does a uint32_t millisecond counter take to wrap around?
   A) About 65 seconds
   B) About 49.7 days
   C) About 136 years
   D) It never wraps

3. last = 4,294,967,000, interval = 500 and now = 4,294,967,100 (no wrap yet). Why does now >= last + interval wrongly report the task as due?
   A) last + interval wraps to 204, and 4,294,967,100 is greater than 204
   B) now is negative
   C) The interval is too short
   D) Unsigned subtraction is undefined

4. Why might you write last += interval instead of last = now after running a periodic task?
   A) It uses less memory
   B) It makes the task run less often
   C) It prevents wrap-around
   D) It keeps the schedule locked to the original timeline, so small lateness does not accumulate into drift

**Go further:**

- Event loop (Wikipedia): https://en.wikipedia.org/wiki/Event_loop — The general idea behind loops that check for work without blocking.


## 3.6 Debugging embedded code

*A systematic way to find bugs in firmware: reproduce, hypothesise and test; serial logging and LEDs as windows into the chip; divide and conquer; and the bugs that catch everyone.* (about 30 min)

### When there is no screen

Your robot's gripper closes, then for no obvious reason opens again. A microcontroller has no screen, and the bug might depend on a motor, a sensor or a timing detail that only happens on the real machine. The core of embedded debugging is not a tool but a method: treat every bug as a small experiment.

### The method: reproduce, hypothesise, test

1. **Reproduce.** Find steps that make the bug happen reliably. A bug you can trigger on demand is half solved.
2. **Observe.** Gather facts before guessing. What exactly happens, and when? What changed since it last worked?
3. **Hypothesise.** Propose one specific cause: "the force reading drops below the threshold when the motor starts."
4. **Test one change at a time.** Design a check that would prove the hypothesis wrong. Change one thing, observe, record. Changing three things at once tells you nothing about which one mattered.
5. **Fix and confirm.** Repeat the original steps and check that the bug is gone and nothing else broke. Keep notes as you go.

### Let the compiler help first

Compile with warnings on (`-Wall`, and ideally `-Wextra`) and read every one. Consider this function, which compiles but contains a classic bug:

```c
#define FAULT 4

int check(int state) {
    if (state = FAULT) {      /* meant ==, compiles anyway */
        return 1;
    }
    return 0;
}
```

The single `=` *assigns* 4 to `state`, and 4 counts as true, so the function always returns 1. With `-Wall`, common compilers warn about using an assignment as a condition. That warning costs nothing and finds a bug that could take an hour on a bench.

### Serial logging

Most microcontrollers can send text to a computer over a serial (UART) connection, which you will study in the embedded communication module. Printing values is the simplest window into a running chip. Good logs have a **timestamp**, a **level** and **specific values**:

```c
#include <stdio.h>
#include <stdint.h>

static uint32_t fake_ms = 0;                     /* stands in for a real clock */
static uint32_t millis_now(void) { return fake_ms; }

#define LOG(level, fmt, ...) \
    printf("[%6lu ms] %s: " fmt "\n", (unsigned long)millis_now(), level, __VA_ARGS__)

int main(void) {
    int raw = 731;
    LOG("INFO", "boot, firmware v%d.%d", 1, 4);
    fake_ms = 1250;
    LOG("DEBUG", "adc raw=%d", raw);
    fake_ms = 1260;
    LOG("WARN", "grip timeout after %d ms", 2000);
    return 0;
}
```

This portable version prints to your terminal:

```
[     0 ms] INFO: boot, firmware v1.4
[  1250 ms] DEBUG: adc raw=731
[  1260 ms] WARN: grip timeout after 2000 ms
```

On a board, the same macro would send its text over the serial port. Logging the firmware version at start-up shows which code is actually running.

**Logging has a cost.** Serial is slow. At 115,200 baud, roughly 11,520 bytes per second get through, because each byte takes about 10 bits on the wire. A 40-character line takes about 40 / 11,520 ≈ 3.5 ms. Add a log line inside a 1 kHz control loop and you have just broken its timing. Worse, the delay can *hide* a timing bug, which then reappears when you remove the log. Log at a reduced rate (for example, one line every 100 passes), log only on changes, or store values in a RAM buffer and print them later.

### LEDs and pins as debug signals

When serial is unavailable or too slow, a spare GPIO pin is a fast, honest signal.

- **Heartbeat:** blink an LED once per second from the main loop. If it stops, the loop is stuck.
- **Blink codes:** flash an LED two times for "sensor missing", three for "timeout", so a fault can be read without a computer.
- **Timing pins:** set a pin high at the start of a function and low at the end. An oscilloscope or logic analyser then shows exactly how long it takes and how often it runs. A pin change takes only a few clock cycles, so it barely disturbs timing.

### Divide and conquer

When you do not know where the bug is, cut the search space in half repeatedly.

- **In the code:** disable half the features. If the bug remains, it is in the other half. Repeat.
- **In history:** if it worked last week, check out a version halfway between then and now, test, and repeat. Version control makes this quick; git even automates it with `git bisect`.
- **In the system:** replace parts with known-good ones. Feed the code a fixed, made-up sensor value. If the bug disappears, look at the sensor side; if not, look at the logic.
- **Make a minimal example:** strip the program down to the fewest lines that still show the bug.

A debug probe, the device used for flashing in the firmware lesson, can also pause the chip at a **breakpoint** and inspect variables, though stopping time can hide timing bugs.

### The usual suspects

Many embedded bugs are one of a short list. Check these early:

- **Hardware first:** is it powered? Do boards share a common ground? Is the wire on the pin the code thinks it is?
- **Pin configuration:** pin never set as output, or input floating without a pull-up.
- **Missing volatile** on a variable shared with an interrupt handler.
- **Integer overflow** or division before multiplication.
- **Array overrun:** a loop such as `for (i = 0; i <= N; i++)` writes one element past the end of an array, silently corrupting whatever variable sits next in RAM. The compiler usually does not warn.
- **Stack overflow** from large local arrays or deep recursion, and **blocking delays** that starve other tasks.
- **Resets caused by power dips:** a motor starting can pull the supply low enough to reset the chip. A boot message in the log reveals this quickly.

Many microcontrollers also have a **watchdog timer**, which resets the chip unless the program "feeds" it regularly. It cannot fix a bug, but it recovers from a hang.

### Recap

Debug like a scientist: reproduce, observe, hypothesise, test one change at a time, then confirm the fix. Turn on compiler warnings first. Use timestamped serial logs, but remember they cost time. Use LEDs and pins for heartbeats, blink codes and timing measurements. Divide and conquer through code, history and hardware. Check the usual suspects, starting with power, ground and wiring, before assuming something exotic.

> **Record what you actually observed.** In your debugging log, separate what you *saw* ("LED stopped blinking at 14:02, after the third grip") from what you *think* ("probably the timeout"). It is tempting to write the hypothesis as if it were the observation, especially once a fix seems to work. Keeping them separate stops you from fooling yourself, and lets someone else check your reasoning.

#### Project: Bug hunt on paper

This made-up firmware fragment is meant to average eight ADC readings and turn on a warning output if the average exceeds 3,000 mV. It contains **at least four bugs** drawn from this lesson. Find them on paper first, then compile a desktop version (replacing `adc_read` with values from an array) to confirm.

```c
#define N 8
uint16_t samples[N];
int alarm_flag;                 /* also set by an interrupt handler */

void update(void) {
    uint16_t total = 0;
    for (int i = 0; i <= N; i++) {
        samples[i] = adc_read(0);
        total += samples[i];
    }
    uint16_t avg_mv = total / N / 1024 * 3300;
    if (alarm_flag = 1 || avg_mv > 3000) {
        set_warning(1);
    }
}
```

For each bug, name the category from "the usual suspects", explain what would go wrong on a real robot, and write the corrected line.

**Deliverables**

- A list of at least four bugs, each with its category and real-world effect
- Corrected code that compiles with cc -std=c99 -Wall without warnings
- A short note on how you would confirm each fix

#### Check your understanding

1. Your control loop's timing problem disappears when you add a print statement, and returns when you remove it. What is the most likely explanation?
   A) The print statement fixed the bug permanently
   B) The compiler ignores print statements
   C) Serial printing takes milliseconds, which changes the loop's timing and hides the real timing bug
   D) Print statements reset the microcontroller

2. You change the sensor code, the filter and the motor gain at once, and the bug disappears. What is the problem with this approach?
   A) You cannot tell which change fixed it, or whether the other changes introduced new problems
   B) Nothing: the bug is gone
   C) Changing code is not allowed while debugging
   D) It will make the compiler produce warnings

3. A loop writes samples[i] for i from 0 to N inclusive, where samples has N elements. What can happen?
   A) The compiler always refuses to build it
   B) The extra write is ignored
   C) The microcontroller always resets immediately
   D) It writes one element past the end, silently corrupting whatever variable is stored next in RAM

4. How can a spare GPIO pin help measure how long a function takes?
   A) Set the pin high at the start and low at the end, and measure the pulse width with an oscilloscope or logic analyser
   B) Connect the pin to the reset line
   C) Read the pin as an analog input
   D) Pins cannot help with timing

5. What does a watchdog timer do?
   A) It speeds up the main loop
   B) It resets the chip if the program stops feeding it regularly, recovering from hangs
   C) It finds bugs automatically
   D) It logs every variable to flash

**Go further:**

- Debugging (Wikipedia): https://en.wikipedia.org/wiki/Debugging — Debugging techniques and tools, including those used for embedded systems.
- Watchdog timer (Wikipedia): https://en.wikipedia.org/wiki/Watchdog_timer — How watchdog timers detect and recover from software hangs.


---

# Module 4: Sensor integration

Turning physical quantities into numbers a program can trust: analogue-to-digital conversion, calibration and filtering.

**Objectives**

- Explain how an analogue-to-digital converter turns a voltage into a number, including resolution.
- Calibrate a sensor reading against known reference values.
- Apply a moving-average filter to reduce noise and describe its cost in delay.
- Recognize common sensor failure modes such as saturation and drift.


## 4.1 Reading and calibrating sensors

*Turning raw ADC counts into trustworthy physical units: the offset-and-gain model, two-point calibration, and checking the result against a third known value.* (about 25 min)

### Why a raw reading is not a measurement

Imagine a robot gripper with a small force sensor in its fingertip. Your firmware reads the analogue-to-digital converter (ADC) and gets the number 1050. Is the gripper squeezing gently or crushing the object? The number alone cannot tell you. It is a count, not a force.

Every analogue sensor sits at the end of a chain: a physical quantity (force, temperature, light) changes something electrical, perhaps via an amplifier, and the ADC turns the resulting voltage into a count. Each link in that chain has its own small errors. Two sensors of the same model, straight from the same box, will rarely give identical counts for the same force. **Calibration** is the process of measuring known reference values so you can convert counts into real units for *your* particular sensor.

### From counts to volts

You met the ADC in the microcontrollers module. A 12-bit ADC gives counts from 0 to 4095, and with a 3.3 V reference the voltage is approximately:

```
V = counts × 3.3 / 4096
```

This matches the microcontrollers module: the reference voltage is divided into 2¹² = 4096 equal steps. (Some datasheets divide by 4095 instead; the difference is less than one count.) So 1838 counts is about 1.481 V. Converting to volts is useful for checking your wiring with a multimeter, but it still is not the quantity you care about. For that you need a model of the sensor.

### The offset-and-gain model

Many sensors are close to **linear**: double the force and the reading rises by double the amount. A straight line needs only two numbers:

```
value = (raw − offset) × gain
```

- The **offset** is the raw reading when the true value is zero. A load cell with nothing on it might read 238 counts rather than 0, because of the amplifier and tiny imbalances in the sensor.
- The **gain** (also called scale factor or sensitivity) is how many units each count is worth, for example grams per count.

Offset errors shift every reading by the same amount. Gain errors are proportional: they are small near zero and grow as the value increases. A kitchen scale that reads 3 g with an empty pan has an offset error; one that reads 1,030 g for a 1 kg bag of sugar but is correct when empty has a gain error.

### Two-point calibration

Because a line is fixed by two points, you can calibrate a linear sensor by measuring two known values.

1. **Zero point.** Remove all load and record the raw reading. Average several readings to reduce noise.
2. **Reference point.** Apply a known value, ideally near the top of the range you care about, and record the raw reading.
3. **Solve.** The offset is the zero reading; the gain is the known value divided by the change in counts.

### Worked example

These numbers are made up for illustration. A load cell reads 238 counts empty and 1838 counts with a 200.0 g reference mass on it.

```
gain   = 200.0 g / (1838 − 238) counts = 200.0 / 1600 = 0.125 g per count
offset = 238 counts
```

A reading of 1050 counts then means (1050 − 238) × 0.125 = 101.5 g.

In Python:

```python
def two_point(raw_zero, raw_ref, ref_value):
    """Return (offset, gain) from two known calibration points."""
    gain = ref_value / (raw_ref - raw_zero)   # grams per count
    offset = raw_zero                         # counts at zero load
    return offset, gain

def to_grams(raw, offset, gain):
    return (raw - offset) * gain

offset, gain = two_point(raw_zero=238, raw_ref=1838, ref_value=200.0)
print(f"offset = {offset} counts, gain = {gain:.4f} g/count")

for raw in [238, 1050, 1838, 3441]:
    print(f"{raw:5d} counts -> {to_grams(raw, offset, gain):7.2f} g")
```

Output:

```
offset = 238 counts, gain = 0.1250 g/count
  238 counts ->    0.00 g
 1050 counts ->  101.50 g
 1838 counts ->  200.00 g
 3441 counts ->  400.38 g
```

The first and third lines are exactly right by construction: the calibration was built from them. That is why they prove nothing.

### Always check with a third point

A calibration is only tested when you measure something it was *not* built from. Suppose you place a 400.0 g mass and read 3441 counts. The calibration says 400.38 g, an error of 0.38 g, or about 0.1 %. That is good evidence the sensor is linear over this range and your reference values were sound.

If the check point had come out at 412 g instead, something would be wrong: perhaps the sensor is not linear, perhaps the reference mass is not what its label says, or perhaps something was touching the pan. A good habit is to record the check-point error alongside the calibration, so anyone using the numbers knows how far to trust them.

### When two points are not enough

- **Non-linear sensors.** Some sensors, such as thermistors and many infrared distance sensors, follow a curve rather than a line. You can measure several points and either fit a curve or store a **lookup table** and interpolate between entries.
- **Drift.** Offsets often change with temperature and age. Many systems re-measure the zero point at start-up (a scale's "tare" button does exactly this) while keeping the gain from a less frequent full calibration.
- **Saturation.** Outside its range, a sensor stops responding: the ADC sticks at 0 or 4095, or the amplifier clips. A calibration says nothing about readings beyond the largest value you tested, so do not extrapolate far past it.
- **Conditions matter.** Calibrate in the way the sensor will be used: mounted, wired and at a similar temperature. A sensor calibrated on a desk and then bolted into a warm motor housing may shift.

### Storing calibration in firmware

Calibration constants belong in one clearly named place, not scattered as magic numbers. On a microcontroller they are often stored in non-volatile memory so each unit can keep its own values. Record *when* the calibration was done and with what reference values, so it can be repeated or audited later.

### Recap

A raw ADC count becomes a measurement only through a model of the sensor. For a linear sensor, value = (raw − offset) × gain, and two known points fix both numbers. Average readings to reduce noise, choose a reference near the top of your working range, and always confirm with a third known value that was not used to build the calibration. Watch for non-linearity, drift and saturation, and keep the calibration in the conditions where the sensor will actually work.

> **Report the check, not just the fit.** A calibration always looks perfect at the points it was built from. When you report sensor accuracy, quote the error at independent check points, say how many readings you averaged, and say what reference you trusted. Never adjust a calibration until a check point "looks right" without recording that you did.

#### Project: Calculator or Python project: calibrate a made-up sensor

The following data are **made up for illustration**. A temperature sensor gives these averaged ADC counts:

- in melting ice (0.0 °C): 621 counts
- in a water bath at 50.0 °C: 2172 counts
- in a water bath at 25.0 °C: 1402 counts

1. Use the 0 °C and 50 °C points to find the offset and gain (in °C per count).
2. Convert the 25 °C reading using your calibration and work out the check-point error.
3. Write a short Python function `counts_to_celsius(raw)` and test it on all three points with `assert` statements that allow a sensible tolerance.
4. In two or three sentences, say whether you would trust this sensor to ±0.5 °C between 0 and 50 °C, and what further test you would run.

No hardware is needed.

**Deliverables**

- Offset and gain with units, showing your working
- The check-point error at 25 °C
- A Python function with assert-based tests
- A short judgement of whether the calibration is good enough

**Safety (adult supervision required):** This project is calculation only. If you later repeat it with a real sensor, use only low-voltage, battery-powered electronics, work with an adult supervising, never put electronics or bare wires into water, and handle hot water with care.

#### Check your understanding

1. A load cell reads 300 counts with no load and 2300 counts with a 500 g mass. What is its gain?
   A) 0.25 g per count
   B) 4 g per count
   C) 0.2174 g per count
   D) 1.667 g per count

2. Using that same calibration (offset 300 counts, gain 0.25 g per count), what does a reading of 1100 counts mean?
   A) 275 g
   B) 200 g
   C) 1100 g
   D) 300 g

3. Why should you test a calibration with a third known value?
   A) Because the ADC needs three readings to start
   B) Because two points cannot define a straight line
   C) Because the calibration fits its own two points exactly, so only an independent point reveals non-linearity or a bad reference
   D) Because it doubles the resolution of the sensor

4. A scale reads 4 g with nothing on it but is accurate for the change in weight when items are added. What kind of error is this?
   A) A gain error
   B) Saturation
   C) Aliasing
   D) An offset error

5. Your calibration used 0 g and 200 g. The firmware now reads a value that converts to 900 g. What is the most careful interpretation?
   A) Trust it fully: the line extends forever
   B) Treat it with caution: it is far outside the calibrated range and the sensor may be non-linear or saturating
   C) It must be exactly 900 g because the gain is constant
   D) It proves the reference mass was wrong

**Go further:**

- Calibration — Wikipedia: https://en.wikipedia.org/wiki/Calibration — An overview of calibration in measurement, including traceability to reference standards.


## 4.2 Noise and filtering

*Why every sensor reading wobbles, and how moving-average and exponential filters smooth it, at the unavoidable cost of delay.* (about 30 min)

### Why readings wobble

Read the same sensor a hundred times while nothing changes, and you will not get the same number a hundred times. A distance sensor pointed at a wall might report 20.4, 19.7, 20.2, 19.5 cm. This variation is **noise**: small, rapid, unpredictable errors added to the true value.

Noise comes from many places: thermal motion of electrons in resistors, electrical interference from motors and switching power supplies, vibration, and the ADC itself, which can only report whole counts. You can reduce noise at the source with good wiring, shielding and stable power. Whatever remains, firmware can reduce by **filtering**.

Noise matters for robots because decisions amplify it. A controller that reacts to every wobble in a sensor will twitch its motors. A gripper that closes when force exceeds a threshold might trigger on a noise spike. Smoothing the signal first makes behaviour calmer and more reliable.

### The key idea: averaging cancels randomness

Random errors are as likely to be positive as negative. If you average several readings, the errors partly cancel while the true value stays. For independent noise, averaging N readings reduces the typical size of the noise by a factor of about √N. Averaging 4 readings halves the noise; averaging 100 reduces it tenfold.

But there is a catch. Averaging over time means mixing in *old* readings. If the true value changes, the average takes time to catch up. Every smoothing filter trades **noise** against **lag**. There is no free lunch, only choices.

### The moving average

A **moving average** of length N reports the mean of the most recent N readings. Each new sample enters the window and the oldest leaves.

A moving average of length N delays a signal by about (N − 1)/2 samples on average, and takes N − 1 samples to fully respond to a sudden step. A longer window is smoother but slower.

On a microcontroller you do not need to re-add N numbers every time. Keep a running sum in a small **ring buffer**: subtract the sample that leaves, add the one that arrives.

```c
#define WINDOW 4

typedef struct {
    float samples[WINDOW];
    float sum;
    int index;
    int count;
} MovingAverage;

float ma_update(MovingAverage *ma, float x)
{
    if (ma->count == WINDOW) {
        ma->sum -= ma->samples[ma->index];   /* drop the oldest */
    } else {
        ma->count++;
    }
    ma->samples[ma->index] = x;
    ma->sum += x;
    ma->index = (ma->index + 1) % WINDOW;    /* wrap around */
    return ma->sum / ma->count;
}
```

Start it with `MovingAverage ma = {0};`. Until the window fills, it averages however many samples it has. One subtle point: with floats, repeatedly adding and subtracting can let tiny rounding errors build up in `sum` over millions of updates. With integer samples this cannot happen, which is one reason firmware often filters raw integer counts.

### The exponential filter

The **exponential moving average** (EMA), also called a first-order low-pass filter, needs only one stored number:

```
y = y + α · (x − y)
```

Here x is the new reading, y is the filtered value and α (alpha) is between 0 and 1. Read it as: "move a fraction α of the way from where you are towards the new reading". With α = 1 there is no filtering at all; with α = 0.1 each reading nudges the output only a little, giving heavy smoothing and slow response.

The name comes from how it weighs the past: the newest reading has weight α, the one before α(1 − α), then α(1 − α)², and so on, fading away exponentially. Nothing is ever completely forgotten, but old readings soon stop mattering.

If you sample every dt seconds and want the filter to have a **time constant** τ (roughly, how long it takes to cover 63 % of a step), choose:

```
α = dt / (τ + dt)
```

For example, sampling at 100 Hz (dt = 0.01 s) with τ = 0.09 s gives α = 0.01 / 0.10 = 0.1.

### Comparing them on real-looking data

These readings are made up for illustration. The true value is 20.0 until sample 8, then genuinely steps to 30.0.

```python
readings = [20.4, 19.7, 20.2, 19.5, 20.6, 19.9, 20.3, 19.6,
            30.2, 29.6, 30.5, 29.8, 30.1, 29.7, 30.4, 29.9]

def moving_average(xs, n):
    out = []
    for i in range(len(xs)):
        window = xs[max(0, i - n + 1): i + 1]
        out.append(sum(window) / len(window))
    return out

def exponential(xs, alpha):
    out = []
    y = xs[0]
    for x in xs:
        y = y + alpha * (x - y)
        out.append(y)
    return out

ma = moving_average(readings, 4)
ema = exponential(readings, 0.3)
print(" k   raw    MA(4)   EMA(0.3)")
for k, (r, m, e) in enumerate(zip(readings, ma, ema)):
    print(f"{k:2d}  {r:5.1f}  {m:6.2f}  {e:7.2f}")
```

Output:

```
 k   raw    MA(4)   EMA(0.3)
 0   20.4   20.40    20.40
 1   19.7   20.05    20.19
 2   20.2   20.10    20.19
 3   19.5   19.95    19.99
 4   20.6   20.00    20.17
 5   19.9   20.05    20.09
 6   20.3   20.07    20.15
 7   19.6   20.10    19.99
 8   30.2   22.50    23.05
 9   29.6   24.93    25.02
10   30.5   27.48    26.66
11   29.8   30.02    27.60
12   30.1   30.00    28.35
13   29.7   30.02    28.76
14   30.4   30.00    29.25
15   29.9   30.02    29.44
```

Before the step, the raw readings span 1.1 units (19.5 to 20.6). After the first sample, which both filters simply copy, the moving average stays within 19.95 to 20.10, and the EMA within 19.99 to 20.19: both are much calmer. After the step, the moving average has fully arrived by sample 11, three samples later, exactly as (N − 1) predicts. The EMA with α = 0.3 is still only at 29.44 seven samples later: each update closes 30 % of the remaining gap, so after the eight updates from sample 8 to sample 15, 0.7⁸ ≈ 6 % of the gap is still left.

Neither filter is "better". The EMA is cheaper in memory; the moving average responds in a fixed, predictable number of samples. A smaller α or a longer window would be smoother still and even slower.

### Spikes need a different tool

Averaging filters spread a single wild reading across several outputs instead of removing it. A **median filter**, which reports the middle value of the last few readings (for example 3 or 5), ignores isolated spikes almost completely while preserving sharp steps. It costs a little sorting. Many sensor pipelines use a short median filter to reject spikes, followed by an EMA to smooth what remains.

### Recap

Noise is unavoidable, and averaging reduces it because random errors cancel. A moving average of length N is simple and responds fully in N − 1 samples; an exponential filter needs only one stored value and is tuned with α = dt / (τ + dt). Every smoothing filter adds lag, so choose the least smoothing your task can tolerate, and use a median filter when the problem is spikes rather than steady wobble.

> **Lag can be dangerous.** In a feedback loop, a heavily filtered sensor tells the controller about the past. A controller acting on old information can overshoot and oscillate, just as the feedback-control lessons warned about delay. If filtering makes a control loop misbehave, try less filtering or a faster sample rate before increasing controller gain.

#### Project: Python project: the noise–lag trade-off

Using the made-up readings in this lesson (or your own list of at least 30 invented readings with a step in the middle):

1. Run the moving average with N = 2, 4 and 8, and the EMA with α = 0.5, 0.3 and 0.1.
2. For each filter, measure (a) the spread (max − min) of its output over the steady part before the step, and (b) how many samples after the step it takes to get within 1.0 of the new value.
3. Print a small results list and describe the pattern you see in two or three sentences.
4. Add one deliberate spike (for example 55.0) to the steady part and compare an EMA with a 3-sample median filter that you write yourself.

No hardware is needed.

**Deliverables**

- A Python script with your filter functions
- A results list of spread and response time for each setting
- A short written comparison, including the spike experiment

#### Check your understanding

1. An EMA has filtered value y = 10.0. A new reading x = 20.0 arrives, and α = 0.25. What is the new y?
   A) 15.0
   B) 12.5
   C) 17.5
   D) 20.0

2. Averaging independent random noise over 16 readings reduces the typical noise size by about what factor?
   A) 16
   B) 8
   C) 2
   D) 4

3. What is the main cost of increasing a moving-average window from 4 to 16 samples?
   A) The filter output responds more slowly to real changes
   B) The noise gets larger
   C) The output can never reach the true value
   D) It stops working on integer data

4. A sensor is usually calm but occasionally produces a single wildly wrong reading. Which filter handles this best?
   A) An EMA with α = 0.9
   B) A short median filter
   C) No filter: spikes average out by themselves
   D) A moving average with a window of 2

5. You sample at 50 Hz (dt = 0.02 s) and want an EMA with time constant τ = 0.18 s. Which α should you use?
   A) 0.18
   B) 0.02
   C) 0.1
   D) 0.9

**Go further:**

- Moving average — Wikipedia: https://en.wikipedia.org/wiki/Moving_average — Simple, weighted and exponential moving averages compared.
- Exponential smoothing — Wikipedia: https://en.wikipedia.org/wiki/Exponential_smoothing — More on the exponential filter, including its link to the time constant.


## 4.3 Combining sensors

*Why two imperfect sensors can beat one good one: complementary strengths, the complementary filter, and a first look at the idea behind the Kalman filter.* (about 35 min)

### No sensor is good at everything

A balancing robot needs to know its tilt angle many times a second. Two cheap sensors can help, and each is flawed in a different way.

- A **gyroscope** measures rotation *rate*, in degrees per second. Add up rate × time and you get the change in angle. Over a fraction of a second this is smooth and accurate. But any small error in the rate, called a **bias**, is added up too. A bias of just 0.5 °/s becomes a 30° error after a minute. This slow wandering is called **drift**.
- An **accelerometer** senses the direction of gravity, so from it you can work out tilt directly. It does not drift: its answer is always about the present. But it is noisy, and every bump or acceleration of the robot looks like a change in gravity's direction.

The gyroscope is good over short times and bad over long ones. The accelerometer is the reverse. Combining them so each covers the other's weakness is called **sensor fusion**, and it appears everywhere in robotics: phones, drones, wheeled robots that combine wheel odometry with a camera, and grippers that combine vision with touch.

### Absolute and relative sensors

It helps to sort sensors into two kinds.

- **Relative** sensors measure *change*: gyroscopes, wheel encoders counting rotations, step counters. You get position or angle by adding up changes, so errors accumulate.
- **Absolute** sensors measure the quantity itself: an accelerometer's gravity direction, a camera seeing a marker, a GPS fix. Errors do not accumulate, but individual readings are noisy, slow, or sometimes missing altogether.

Fusion usually means: use the relative sensor to **predict** smoothly from moment to moment, and use the absolute sensor to **correct** the slow drift.

### The complementary filter

The simplest fusion method fits in one line:

```
angle = α · (angle + gyro_rate · dt) + (1 − α) · accel_angle
```

The first part is a prediction: last estimate plus the gyroscope's change. The second part pulls the estimate gently towards the accelerometer's absolute answer. With α = 0.98, each update trusts the prediction 98 % and the accelerometer 2 %.

Why does this work? Over a short time, the 2 % pull is too weak to let the accelerometer's noise through, so the output is smooth like the gyroscope. Over a long time, that small pull adds up and steadily drags away any drift, so the output stays anchored like the accelerometer. In effect, the gyroscope signal is high-pass filtered, the accelerometer signal is low-pass filtered, and the two filters complement each other, which is where the name comes from.

The crossover time between "trust the gyro" and "trust the accelerometer" is:

```
τ = α · dt / (1 − α)
```

At 100 Hz (dt = 0.01 s) with α = 0.98, τ = 0.98 × 0.01 / 0.02 = 0.49 s. Changes faster than about half a second come mostly from the gyroscope; slower ones mostly from the accelerometer.

### Worked example

The numbers below are made up for illustration. The robot is held still at a true tilt of 10°. The gyroscope has a bias of 0.5 °/s; the accelerometer's reading has errors of up to 3°.

```python
dt = 0.01                                   # 100 samples per second
alpha = 0.98
gyro_bias = 0.5                             # deg/s error in the gyro
accel_noise = [2.0, -3.0, 1.0, -1.5, 1.5, -0.5, 0.5]  # repeating error, deg

true_angle = 10.0
gyro_only = 10.0          # start both estimates at the right answer
fused = 10.0

for k in range(1, 1001):
    gyro_rate = 0.0 + gyro_bias                      # true rate is zero
    accel_angle = true_angle + accel_noise[k % 7]

    gyro_only = gyro_only + gyro_rate * dt
    fused = alpha * (fused + gyro_rate * dt) + (1 - alpha) * accel_angle

    if k % 250 == 0:
        print(f"t = {k * dt:5.2f} s  gyro only {gyro_only:6.2f}"
              f"  accel {accel_angle:6.2f}  fused {fused:6.2f}")
```

Output:

```
t =  2.50 s  gyro only  11.25  accel   9.50  fused  10.24
t =  5.00 s  gyro only  12.50  accel   8.50  fused  10.22
t =  7.50 s  gyro only  13.75  accel   7.00  fused  10.23
t = 10.00 s  gyro only  15.00  accel  10.50  fused  10.25
```

The gyroscope alone drifts steadily, 5° wrong after 10 seconds and getting worse. The accelerometer alone jumps around by up to 3°. The fused estimate stays within about a quarter of a degree, and stays there. That small leftover error is predictable: a complementary filter settles with an error of about bias × τ = 0.5 × 0.49 ≈ 0.25°. Raising α makes the output smoother but leaves more of the gyro bias in; lowering it removes bias faster but lets more accelerometer noise through.

### A preview of the Kalman idea

The complementary filter uses a fixed α that *you* choose. A smarter question is: how much should I trust each sensor, given how noisy each one is right now?

Suppose two sensors measure the same distance, with typical errors (standard deviations) σ₁ = 3 cm and σ₂ = 4 cm. The best way to average them weights each by the inverse of its variance (σ²):

```
w₁ = σ₂² / (σ₁² + σ₂²) = 16 / 25 = 0.64
w₂ = σ₁² / (σ₁² + σ₂²) =  9 / 25 = 0.36
fused σ = √(σ₁² · σ₂² / (σ₁² + σ₂²)) = √(144 / 25) = 2.4 cm
```

If they read 52.0 cm and 47.0 cm, the fused estimate is 0.64 × 52.0 + 0.36 × 47.0 = 50.2 cm. Notice that the combined uncertainty, 2.4 cm, is smaller than *either* sensor alone. That is the core promise of fusion.

A **Kalman filter** applies this weighting at every time step. It keeps track of its own uncertainty: uncertainty grows during each prediction (because the relative sensor drifts) and shrinks at each correction (because the absolute sensor adds information). When the absolute sensor goes quiet, the filter knows it is becoming less certain and leans entirely on prediction; when a measurement arrives, it weights it according to how uncertain it has become. A Kalman filter can even estimate the bias itself, as an extra unknown, and subtract it. The full mathematics uses matrices and is beyond this lesson, but the intuition is just this: **weight each source by how much you trust it, and keep track of how much you trust yourself.**

### Try it in the explorer

The explorer below fuses two sensors watching a point moving along a line. The **camera** is the absolute sensor: noisy, and sometimes blocked entirely for a second or so. **Odometry** is the relative sensor: always available but biased, so it drifts. The complementary option uses exactly the formula above, applied whenever a camera frame arrives: estimate = α · prediction + (1 − α) · camera.

> **Interactive:** Choose the complementary filter and move the blend α between 0.5 and 0.99: watch the trade between camera noise getting through and odometry drift during dropouts. Then raise the odometry bias and dropout probability, and switch to the Kalman filter to see its uncertainty band widen during each dropout and its bias estimate converge. This is an illustrative simulation, not measured data. Try it at https://tactiverge.win/academy/lab/#fusion

### What to notice

When the camera disappears, every fused estimate falls back on odometry and starts to drift; the longer the dropout, the bigger the error. When the camera returns, the estimate is pulled back. The Kalman filter usually recovers more cleverly because it has also learned the odometry bias while the camera could see, so it drifts less during the gap.

The explorer is honest about its simplifications: its noise is perfectly random, the Kalman filter is told the true noise levels, and the camera has no delay. Real systems have to estimate noise levels and handle late measurements, which the lesson on timestamps returns to.

### Recap

Relative sensors are smooth but drift; absolute sensors do not drift but are noisy or intermittent. Fusion predicts with the first and corrects with the second. The complementary filter does this with one fixed weight α, giving a crossover time τ = α · dt / (1 − α) and a predictable leftover bias error. The Kalman filter chooses its weights from each source's uncertainty, tracks its own confidence, and can estimate sensor bias, which is why it is the standard tool when accuracy matters.

#### Check your understanding

1. Why is a gyroscope's angle estimate said to drift?
   A) Its readings are delayed by several seconds
   B) Small errors in measured rate are added up over time, so the angle error keeps growing
   C) It only works when the robot is moving
   D) It measures the direction of gravity, which changes

2. A complementary filter runs at 50 Hz (dt = 0.02 s) with α = 0.95. What is its crossover time constant τ?
   A) 0.95 s
   B) 0.019 s
   C) 0.02 s
   D) 0.38 s

3. Two sensors measure the same quantity with σ₁ = 1 cm and σ₂ = 2 cm. With inverse-variance weighting, what weight goes on sensor 1?
   A) 0.8
   B) 0.5
   C) 0.33
   D) 0.2

4. In a complementary filter, what happens if you raise α closer to 1?
   A) The output follows the absolute sensor more closely
   B) Drift is removed faster
   C) The output is smoother, but drift from the relative sensor is corrected more slowly
   D) The filter becomes a Kalman filter

5. What can a Kalman filter do that a basic complementary filter cannot?
   A) Work without any sensors
   B) Track its own uncertainty and adjust how much it trusts each measurement accordingly
   C) Guarantee zero error
   D) Avoid needing a model of how the system moves

**Go further:**

- Sensor fusion — Wikipedia: https://en.wikipedia.org/wiki/Sensor_fusion — An overview of fusion methods, including the inverse-variance weighting used here.
- Kalman filter — Wikipedia: https://en.wikipedia.org/wiki/Kalman_filter — The full algorithm with its matrix mathematics. Demanding, but the opening sections explain the predict–update idea well.


## 4.4 Sampling rate and aliasing

*What happens between samples: the Nyquist limit, how fast signals masquerade as slow ones, and how to choose a sample rate and an anti-aliasing filter.* (about 30 min)

### A program only sees snapshots

A microcontroller does not watch a sensor continuously. It takes a **sample** at regular intervals and knows nothing about what happens in between. The number of samples per second is the **sample rate**, fs, measured in hertz (Hz).

This raises a practical question for every sensor in a robot: how often should you read it? Too slowly, and you miss events or, worse, see things that are not there. Too quickly, and you waste processor time, power and memory. This lesson gives you the tools to choose.

### The wagon-wheel effect

You may have seen a film where a car's wheels appear to spin slowly backwards while the car speeds forwards. The camera samples at a fixed frame rate. If a wheel spoke moves almost a full spoke-spacing between frames, it looks as if it moved a tiny bit *backwards*. A fast motion has disguised itself as a slow one.

The same thing happens to sensor signals. It is called **aliasing**, because a fast signal appears under a false identity, an alias.

### Seeing an alias in numbers

Sample a 9 Hz signal at 10 Hz, and compare it with a 1 Hz signal sampled at the same moments:

```python
import math

fs = 10.0                                  # samples per second
for n in range(6):
    t = n / fs
    fast = math.cos(2 * math.pi * 9 * t)   # a 9 Hz signal
    slow = math.cos(2 * math.pi * 1 * t)   # a 1 Hz signal
    print(f"t = {t:.1f} s   9 Hz: {fast:+.3f}   1 Hz: {slow:+.3f}")
```

Output:

```
t = 0.0 s   9 Hz: +1.000   1 Hz: +1.000
t = 0.1 s   9 Hz: +0.809   1 Hz: +0.809
t = 0.2 s   9 Hz: +0.309   1 Hz: +0.309
t = 0.3 s   9 Hz: -0.309   1 Hz: -0.309
t = 0.4 s   9 Hz: -0.809   1 Hz: -0.809
t = 0.5 s   9 Hz: -1.000   1 Hz: -1.000
```

The samples are identical. Once sampled, there is no way to tell them apart: the information that would distinguish them is simply gone. No clever software afterwards can undo this, which is the most important point in this lesson.

### The Nyquist limit

The rule that tells you when this happens is usually called the **Nyquist–Shannon sampling theorem**. In plain words:

> To capture a signal faithfully, you must sample at more than twice its highest frequency.

Half the sample rate, fs / 2, is called the **Nyquist frequency**. Anything in the signal below it is captured correctly. Anything above it folds back and appears as a lower frequency. For a single sine wave of frequency f, the apparent frequency is the distance from f to the nearest whole multiple of fs:

```python
def alias_frequency(f, fs):
    """Frequency that a sine of f Hz appears to have when sampled at fs Hz."""
    k = round(f / fs)           # nearest whole multiple of fs
    return abs(f - k * fs)

for f, fs in [(9, 10), (3, 10), (50, 40), (60, 50), (100, 1000)]:
    print(f"{f:4d} Hz sampled at {fs:4d} Hz looks like {alias_frequency(f, fs):g} Hz")
```

Output:

```
   9 Hz sampled at   10 Hz looks like 1 Hz
   3 Hz sampled at   10 Hz looks like 3 Hz
  50 Hz sampled at   40 Hz looks like 10 Hz
  60 Hz sampled at   50 Hz looks like 10 Hz
 100 Hz sampled at 1000 Hz looks like 100 Hz
```

The 3 Hz and 100 Hz signals are below their Nyquist frequencies (5 Hz and 500 Hz) and come through honestly. The others do not.

### A realistic trap: mains hum

Mains electricity alternates at 50 Hz or 60 Hz depending on the country, and long sensor wires near mains cables or motors can pick up a little of it. Suppose you read a temperature sensor at 40 Hz in a building with 50 Hz mains. The hum folds down to 10 Hz, and your temperature appears to wobble ten times a second. Worse, a hum frequency very close to a multiple of your sample rate produces an alias of a fraction of a hertz, which looks just like a slow, real change in temperature. An alias does not look like noise; it looks like data.

### Preventing aliasing

There are two defences, and good designs use both.

1. **Sample fast enough** for the frequencies you care about.
2. **Remove what you do not care about before sampling**, using an **anti-aliasing filter**: a low-pass filter in the analogue circuit, in front of the ADC. The simplest is a resistor and capacitor (an RC filter), with cutoff frequency:

```
fc = 1 / (2π · R · C)
```

With R = 10 kΩ and C = 1 µF, fc = 1 / (2π × 10,000 × 0.000001) ≈ 15.9 Hz. Signals well above that are strongly reduced before the ADC ever sees them. A single RC stage rolls off gently, so it reduces rather than eliminates high frequencies; demanding applications use steeper filters. Note that a *digital* filter in firmware, like the moving average, cannot fix aliasing, because by the time the data reaches it the damage is done.

Choosing R also matters for the ADC: many ADCs need a low enough source resistance to charge their internal sampling capacitor in time. Check your microcontroller's datasheet for its recommended maximum.

### Choosing a sample rate

Nyquist gives a hard minimum, but practical systems sample well above it.

- **For control loops**, a common rule of thumb is to sample at least 10 times faster than the fastest behaviour you are trying to control. A joint that settles in about 0.1 s has important behaviour up to roughly 10 Hz, suggesting a loop rate of 100 Hz or more.
- **For monitoring slow quantities** like battery voltage or temperature, a few samples per second may be plenty, as long as an anti-aliasing filter blocks faster interference.
- **For signals with sharp events**, like a bump switch or a force spike when a gripper touches an object, sample fast enough that the event lasts several samples, or use an interrupt.
- **Oversampling and averaging**: sampling faster than needed and averaging groups of samples reduces noise, and is a cheap trick on microcontrollers with spare ADC time.

Always check the cost side too: every sample uses processor time and, if logged, storage. At 1 kHz, a 2-byte reading fills 2 KB per second, which is over 7 MB per hour.

### Recap

A sampled signal only contains information below half the sample rate. Anything faster folds down and impersonates a slower signal, and no software can separate the two afterwards. Prevent aliasing by sampling comfortably fast and by low-pass filtering in hardware before the ADC. Choose rates from the speed of the behaviour you care about, typically ten times faster for control, and remember that a digital filter cannot undo aliasing.

> **Sample rate is not the same as response speed.** Reading a sensor at 1 kHz is pointless if the sensor itself only updates 10 times a second internally: you will just read the same value 100 times. Check how fast a sensor actually produces new data (its output data rate or bandwidth) before deciding how often to read it.

#### Project: Python project: an alias hunter

1. Extend the alias example: sample a 7 Hz cosine at fs = 8, 10, 14, 15 and 50 Hz. For each, print the first 10 samples and predict the alias frequency with `alias_frequency` before you run it.
2. For fs = 10 Hz, print the apparent frequency of every whole-number input frequency from 0 to 30 Hz. Describe the zig-zag pattern you see, and explain where it turns around.
3. Calculate the RC cutoff frequency for three resistor and capacitor combinations of your choice, and say which would be a sensible anti-aliasing filter for a sensor read at 100 Hz.

This is a paper-and-Python activity. No hardware is required.

**Deliverables**

- Python output with your predictions alongside
- A short description of the folding pattern for fs = 10 Hz
- Three RC cutoff calculations with a recommendation

**Safety (adult supervision required):** This is a calculation-only activity. If you go on to build an RC filter on a breadboard, use only low-voltage battery power, check component ratings, and work with an adult supervising.

#### Check your understanding

1. A sensor is sampled at 200 Hz. What is its Nyquist frequency?
   A) 400 Hz
   B) 200 Hz
   C) 100 Hz
   D) 50 Hz

2. A 45 Hz vibration is sampled at 50 Hz. What frequency does it appear to have?
   A) 5 Hz
   B) 45 Hz
   C) 95 Hz
   D) 25 Hz

3. Your data shows a mysterious slow oscillation. You suspect aliasing. Which fix will NOT help?
   A) Adding an analogue low-pass filter before the ADC
   B) Increasing the sample rate
   C) Applying a moving-average filter to the samples already recorded
   D) Shielding wires and moving them away from the interference source

4. Using the rule of thumb from this lesson, roughly what loop rate suits a joint whose important behaviour reaches about 20 Hz?
   A) About 40 Hz exactly
   B) About 20 Hz
   C) About 4 Hz
   D) About 200 Hz or more

5. What is the cutoff frequency of an RC filter with R = 1 kΩ and C = 1 µF?
   A) About 1.6 Hz
   B) About 159 Hz
   C) About 1000 Hz
   D) About 15.9 kHz

**Go further:**

- Nyquist–Shannon sampling theorem — Wikipedia: https://en.wikipedia.org/wiki/Nyquist%E2%80%93Shannon_sampling_theorem — The theorem stated precisely, with its history and assumptions.
- Aliasing — Wikipedia: https://en.wikipedia.org/wiki/Aliasing — Visual examples of aliasing in signals and images, including the folding of frequencies.
- Anti-aliasing filter — Wikipedia: https://en.wikipedia.org/wiki/Anti-aliasing_filter — Why filters go before the converter, and how steep they need to be.


## 4.5 Units, scaling and fixed-point arithmetic

*Doing accurate maths with integers on small processors: choosing scaled units, ordering operations to avoid truncation and overflow, and Q-format fixed point.* (about 30 min)

### Why not just use floats?

On a laptop, `float` and `double` arithmetic is fast and you rarely think about it. Many small microcontrollers have no hardware floating-point unit. The compiler still lets you write `float`, but each operation becomes a call into a software library: slower, larger in flash, and sometimes too slow for a fast control loop. Even on chips with floating-point hardware, integers remain attractive for interrupt handlers, compact data logs and messages between devices.

The alternative is to do maths with integers, deliberately scaled so they keep enough precision. Done carefully, this is fast and exact. Done carelessly, it produces some of the most baffling bugs in embedded systems. This lesson builds on fixed-width types and overflow from the programming-foundations module.

### Units first

Before any arithmetic, decide what every number *means*. A variable called `temp` holding 2500 is ambiguous: 2500 °C? 25.00 °C? 2500 counts? Good firmware puts the unit in the name:

```c
int32_t temp_cdeg;    /* hundredths of a degree Celsius: 2500 means 25.00 °C */
int32_t battery_mv;   /* millivolts                                          */
uint32_t uptime_ms;   /* milliseconds since start-up                         */
```

Choosing a smaller unit, such as millivolts instead of volts or centidegrees instead of degrees, is the simplest form of fixed point. The integer counts tiny steps, and the step size sets the resolution. Millivolts give a resolution of 0.001 V with no fractions at all.

Unit confusion is not a beginner's problem. NASA's Mars Climate Orbiter was lost in 1999 partly because one piece of software produced results in pound-force seconds while another expected newton-seconds. Labelled units are cheap insurance.

### Order of operations matters

Converting a 12-bit ADC reading to millivolts with a 3.3 V reference means calculating counts × 3300 / 4096. In integer maths, the order and the width of the variables change the answer completely:

```c
#include <stdio.h>
#include <stdint.h>

int main(void)
{
    uint16_t counts = 2000;                  /* 12-bit ADC reading */

    /* Wrong 1: divide first. 2000 / 4096 is 0 in integer maths. */
    int32_t mv_div_first = counts / 4096 * 3300;

    /* Wrong 2: a 16-bit intermediate overflows (2000 * 3300 = 6,600,000). */
    uint16_t mv_16bit = (uint16_t)(counts * 3300u);

    /* Right: widen to 32 bits, multiply first, then divide. */
    int32_t mv = (int32_t)counts * 3300 / 4096;

    /* Better: add half the divisor first to round to nearest. */
    int32_t mv_rounded = ((int32_t)counts * 3300 + 4096 / 2) / 4096;

    printf("divide first: %ld mV\n", (long)mv_div_first);
    printf("16-bit:       %u mV\n", (unsigned)mv_16bit);
    printf("32-bit:       %ld mV\n", (long)mv);
    printf("rounded:      %ld mV\n", (long)mv_rounded);
    return 0;
}
```

Output:

```
divide first: 0 mV
16-bit:       46400 mV
32-bit:       1611 mV
rounded:      1611 mV
```

The exact answer is 1611.33 mV, so here rounding and truncating agree; try 2003 counts (1613.75 mV), where truncating gives 1613 and rounding gives 1614. Look at each line:

- **Divide first** throws away everything: integer division truncates 2000 / 4096 to 0.
- **The 16-bit result** wrapped around. 6,600,000 does not fit in 16 bits (maximum 65,535), and 6,600,000 mod 65,536 = 46,400. The cast here imitates what happens on a processor whose `int` is 16 bits wide, where the multiplication itself overflows.
- **32-bit, multiply first** keeps the precision; the largest possible intermediate, 4095 × 3300 = 13,513,500, fits easily in an `int32_t` (maximum about 2.1 billion).
- **Rounding**: integer division always rounds towards zero. Adding half the divisor first rounds to the nearest whole number instead. (For negative numbers you would subtract it; check the sign.)

The general rules: **multiply before you divide, make sure the intermediate cannot overflow, and decide how you want to round.** Before writing a scaling line, work out the largest value any intermediate can reach.

### Chaining conversions

Suppose an illustrative temperature sensor outputs 500 mV at 0 °C and rises by 10 mV per °C. In centidegrees:

```
temp_cdeg = (sensor_mv − 500) × 10
```

So 750 mV gives (750 − 500) × 10 = 2500, meaning 25.00 °C, and 430 mV gives −700, meaning −7.00 °C. Note that the result can be negative, so it must live in a signed type. Every step stays in integers.

### Q formats: fractions in integers

Sometimes you need genuine fractions, such as a filter coefficient of 0.3 or a gain of 1.5. **Q format** fixed point stores a number multiplied by a power of two. In **Q16.16**, the stored integer is the value × 65,536 (2¹⁶): 16 bits for the whole part, 16 for the fraction.

```
1.5   → 1.5 × 65536   =  98304
2.25  → 2.25 × 65536  = 147456
```

Adding two Q16.16 numbers is ordinary integer addition. Multiplying needs care: the product has 32 fractional bits, so you multiply in 64 bits and shift right by 16:

```
(98304 × 147456) >> 16 = 14495514624 >> 16 = 221184  → 221184 / 65536 = 3.375
```

And 1.5 × 2.25 is indeed 3.375. Powers of two are used because shifting is very cheap on any processor. Another common choice, **Q15**, stores values between −1 and just under +1 in an `int16_t`, popular in audio and signal processing.

### Fixed-point filters and the stuck-filter bug

The exponential filter from the noise lesson is easy to write in integers with α = 1/4: `y += (x − y) / 4`. But watch what happens when the filter approaches its target:

```c
#include <stdio.h>
#include <stdint.h>

int main(void)
{
    int32_t target = 100;
    int32_t plain = 0;      /* filter state in whole units          */
    int32_t scaled = 0;     /* filter state in 1/16ths (4 extra bits) */

    for (int k = 1; k <= 30; k++) {
        plain  += (target - plain) / 4;              /* alpha = 1/4 */
        scaled += (target * 16 - scaled) / 4;
        if (k % 10 == 0) {
            printf("k=%2d  plain=%ld  scaled=%ld (= %ld.%02ld)\n", k,
                   (long)plain, (long)scaled,
                   (long)(scaled / 16), (long)(scaled % 16 * 100 / 16));
        }
    }
    return 0;
}
```

Output:

```
k=10  plain=93  scaled=1508 (= 94.25)
k=20  plain=97  scaled=1593 (= 99.56)
k=30  plain=97  scaled=1597 (= 99.81)
```

The plain filter gets **stuck at 97**: once the gap is less than 4, (100 − 97) / 4 truncates to 0 and nothing ever changes again. Keeping the filter state with 4 extra fractional bits (in sixteenths) lets it creep to within 0.2 of the target. The lesson generalises: keep extra fractional bits in any value that accumulates small changes, and only round when you output the result.

### Recap

Integers are fast and exact, but only if you design their scaling. Put units in variable names and pick small units like millivolts or centidegrees. Multiply before dividing, check the largest intermediate fits, and choose your rounding. Use Q formats when you need fractions, with wider intermediates for multiplication, and keep extra fractional bits in filters and accumulators so small changes are not truncated away.

> **Signed shifts and division.** In C99, shifting a negative signed integer right gives an implementation-defined result, and integer division rounds towards zero rather than down. Code like `y >> 2` on a negative value may not equal `y / 4`. When values can be negative, prefer plain division or test the behaviour on your compiler, and write a comment saying which you rely on.

#### Project: Programming project: integer-only conversion

Write a C99 or Python program (in Python, use only `//` integer division and no floats) that converts 10-bit ADC readings (0 to 1023) with a 5000 mV reference into millivolts using only integers.

1. Implement truncating and rounding versions, and compare both with the exact floating-point answer for every input from 0 to 1023. Report the largest error for each.
2. Work out the largest intermediate value and state the smallest integer type that safely holds it.
3. Implement an integer exponential filter with α = 1/8, with and without 3 extra fractional bits, and show where each settles for a constant input of 500.

This is a computer-only activity. No hardware is needed.

**Deliverables**

- Source code with units in every variable name
- The largest error of the truncating and rounding conversions
- The largest intermediate value and chosen type, with reasoning
- Settled values of both integer filters

#### Check your understanding

1. In C integer arithmetic, what is 3000 / 4096 * 3300?
   A) 2416
   B) 3300
   C) 0
   D) It causes a compile error

2. Why does counts * 3300 risk overflow on a processor with a 16-bit int?
   A) Because 3300 is not a power of two
   B) Because the product can reach millions, far beyond the 16-bit maximum of 65,535
   C) Because multiplication is not allowed on 16-bit processors
   D) Because counts is unsigned

3. What value represents 0.75 in Q16.16 format?
   A) 75
   B) 65536
   C) 0.75
   D) 49152

4. An integer filter y += (x − y) / 8 stops changing before it reaches the input. What is the best fix?
   A) Keep the filter state with extra fractional bits and round only on output
   B) Use a larger α so that it overshoots
   C) Reset the filter every second
   D) Use an unsigned type

5. Why is temp_cdeg a better variable name than temp?
   A) Shorter names compile faster
   B) It states the unit, hundredths of a degree, so nobody misreads 2500 as 2500 degrees
   C) The compiler checks units written in names
   D) It makes the variable floating point

**Go further:**

- Fixed-point arithmetic — Wikipedia: https://en.wikipedia.org/wiki/Fixed-point_arithmetic — Scaling, rounding and overflow in fixed-point maths in more depth.
- Q (number format) — Wikipedia: https://en.wikipedia.org/wiki/Q_(number_format) — The Q notation, with the rules for addition, multiplication and division.
- Mars Climate Orbiter — Wikipedia: https://en.wikipedia.org/wiki/Mars_Climate_Orbiter — The mission and the unit mismatch that contributed to its loss.


## 4.6 Building a reliable sensor pipeline

*Designing sensor code that notices when something is wrong: range and plausibility checks, timeouts, status flags and safe responses to failure.* (about 30 min)

### Sensors fail, and they rarely announce it

A sensor that stops working completely is the easy case. Much more common, and much more dangerous, is a sensor that keeps producing numbers that are wrong. A loose connector can make an analogue input float and read random values. A distance sensor can report 0 cm when it sees nothing. A sensor on a communication bus can lock up and keep returning its last value forever. If the rest of the robot believes those numbers, a gripper might squeeze too hard or a wheel might drive into a wall.

A **reliable sensor pipeline** is code that turns raw readings into values the rest of the system can trust, *and* says clearly when it cannot. Everything in this module so far, calibration, filtering, sampling and fixed-point scaling, fits into it.

### The stages of a pipeline

A typical pipeline has these stages, in this order:

1. **Acquire** the raw reading and record *when* it was taken.
2. **Validate** the raw data: did the read succeed, is it within the possible range of the device?
3. **Convert** to physical units using the calibration.
4. **Check plausibility** against physics and recent history.
5. **Filter** to reduce noise, using only values that passed the checks.
6. **Publish** the value together with a **status** and a **timestamp**, so users know how far to trust it.

Separating these stages makes each one simple and testable, and makes it obvious where a problem was detected.

### Range checks

The simplest check: is the value possible at all? Every sensor has a stated measuring range, and an ADC has a known count range. A raw count pinned at exactly 0 or exactly the maximum often means a short circuit, an open circuit or saturation rather than a real measurement. Many designers deliberately arrange the circuit so that a broken wire produces an obviously impossible value, which makes the fault detectable.

### Plausibility checks

A reading can be in range and still impossible. Physics limits how fast real things change. If a robot moves at most 2 m/s, a distance sensor read every 0.1 s cannot honestly change by more than 20 cm between readings. A **rate-of-change check** rejects bigger jumps.

Here is a small example with made-up readings:

```python
# Made-up distance readings (cm) for illustration, one every 0.1 s.
readings = [82.0, 81.5, 80.9, 0.0, 80.1, 79.6, 312.0, 78.8, 78.3, 650.0]

MIN_CM, MAX_CM = 2.0, 400.0    # the sensor's stated range
MAX_STEP_CM = 20.0             # most the distance can change in 0.1 s

def check(reading, last_good):
    if not (MIN_CM <= reading <= MAX_CM):
        return "OUT_OF_RANGE"
    if last_good is not None and abs(reading - last_good) > MAX_STEP_CM:
        return "IMPLAUSIBLE_JUMP"
    return "OK"

last_good = None
for k, r in enumerate(readings):
    status = check(r, last_good)
    if status == "OK":
        last_good = r
    print(f"{k}: {r:6.1f} cm  {status}")
```

Output:

```
0:   82.0 cm  OK
1:   81.5 cm  OK
2:   80.9 cm  OK
3:    0.0 cm  OUT_OF_RANGE
4:   80.1 cm  OK
5:   79.6 cm  OK
6:  312.0 cm  IMPLAUSIBLE_JUMP
7:   78.8 cm  OK
8:   78.3 cm  OK
9:  650.0 cm  OUT_OF_RANGE
```

The 312 cm reading is inside the sensor's range, so a range check alone would have accepted it. Only the plausibility check, knowing the robot cannot move 2.3 m in a tenth of a second, catches it.

Plausibility checks have a trap. Suppose an object suddenly moves out of the way and the true distance really does jump from 80 cm to 300 cm. A check that always compares with the last good value will reject every new reading forever. Practical code counts consecutive rejections and, after a few in a row that agree with each other, either accepts the new value or raises a fault for a human to look at. Always ask: *how does my check recover?*

Other useful plausibility tests:

- **Stuck-value detection**: a real, noisy sensor almost never returns exactly the same value hundreds of times in a row. Perfectly constant output can mean a frozen device.
- **Cross-checks**: compare sensors that should agree, such as a wheel encoder's speed and a motor current, or two independent temperature sensors.
- **Consistency with commands**: if the motor is commanded forward but the encoder shows no movement, something is jammed, slipping or disconnected.

### Timeouts and stale data

Data has a shelf life. A distance reading from two seconds ago says little about a moving robot now. Every published value should carry the time it was *measured*, and anything that uses it should check its age. Using the wrap-safe elapsed-time pattern from the non-blocking timing lesson:

```c
#include <stdint.h>
#include <stdbool.h>

typedef enum { SENSOR_OK, SENSOR_OUT_OF_RANGE, SENSOR_IMPLAUSIBLE, SENSOR_STALE } SensorStatus;

typedef struct {
    float value_cm;        /* last value that passed every check   */
    uint32_t stamp_ms;     /* when that value was measured          */
    SensorStatus status;   /* the result of the most recent check   */
} DistanceReading;

#define MIN_CM 2.0f
#define MAX_CM 400.0f
#define MAX_STEP_CM 20.0f
#define TIMEOUT_MS 300u

/* Called whenever a new raw reading arrives. */
void distance_update(DistanceReading *d, float raw_cm, uint32_t now_ms, bool have_previous)
{
    if (raw_cm < MIN_CM || raw_cm > MAX_CM) {
        d->status = SENSOR_OUT_OF_RANGE;
    } else if (have_previous && (raw_cm - d->value_cm > MAX_STEP_CM || d->value_cm - raw_cm > MAX_STEP_CM)) {
        d->status = SENSOR_IMPLAUSIBLE;
    } else {
        d->value_cm = raw_cm;
        d->stamp_ms = now_ms;
        d->status = SENSOR_OK;
    }
}

/* Called every loop, even when no reading arrived. Wrap-safe subtraction. */
bool distance_is_fresh(const DistanceReading *d, uint32_t now_ms)
{
    return (uint32_t)(now_ms - d->stamp_ms) <= TIMEOUT_MS;
}
```

Notice that the value and its status travel together in one struct. Code that uses the distance cannot easily forget to check whether it is trustworthy. The freshness check runs every loop, so a sensor that silently stops sending is detected within 300 ms even though no "error" ever arrived.

### Deciding what to do about a fault

Detecting a problem is only half the job. The system must respond in a way that is **safe**, which depends on the machine:

- **Hold the last good value** briefly, for short glitches, but only for a bounded time and with the status marked accordingly.
- **Fall back** to another sensor, as fusion does when a camera drops out.
- **Degrade gracefully**: slow down, reduce force, or switch to a more cautious mode.
- **Stop safely**: for a moving robot, stopping its motors is often the safe state. For some machines, such as a robot holding a load, stopping suddenly is not safe, and the safe response must be designed specifically.

Whatever happens, **log it**: what was detected, when, and what the system did. Faults that are silently "fixed" in firmware cannot be investigated later.

### Recap

A reliable pipeline acquires, validates, converts, checks plausibility, filters and publishes, attaching a status and a measurement timestamp to every value. Range checks catch impossible numbers; plausibility checks catch possible-but-wrong ones, provided they can recover from genuine jumps. Timeouts catch sensors that go quiet. Decide in advance what safe response each fault gets, and record every fault rather than hiding it.

> **Firmware checks are not a safety system on their own.** Plausibility checks make a robot more dependable, but they run on the same processor that might itself crash. Machines that could hurt someone also need independent protection, such as a hardware emergency stop that cuts actuator power and does not depend on software. If you build anything with motors, keep it small and low-voltage, and work with an adult supervising.

#### Project: Paper and Python project: design a fault table

Choose a sensor from this module, for example the load cell in a gripper or a distance sensor on a small wheeled robot.

1. List at least **five** ways it could fail or mislead (for example: broken wire, saturation, frozen bus device, electrical noise, sensor knocked out of alignment).
2. For each failure, write how your pipeline would detect it (which check, with what threshold and why) and what the safe response would be.
3. Extend the Python example so that after **three** consecutive rejected readings that agree with each other to within 5 cm, the new value is accepted and a message is printed. Test it with a made-up list containing a genuine jump.

This is a paper-and-computer activity. No hardware is required.

**Deliverables**

- A fault list with detection method, threshold and safe response for each item
- Extended Python code with its test data and output
- Two sentences on one fault your checks could still miss

#### Check your understanding

1. A distance sensor rated for 2–400 cm reports 250 cm, immediately after reporting 60 cm, 0.05 s earlier, on a robot that moves at most 1 m/s. Which check flags it?
   A) The range check
   B) The timeout check
   C) The rate-of-change plausibility check
   D) None: the reading is fine

2. Why should each published sensor value carry the time it was measured?
   A) So that users can detect stale data and align it with other sensors
   B) Because the ADC requires it
   C) To make the values more precise
   D) So the filter can run faster

3. A sensor on a bus locks up and keeps returning exactly the same number. Which check is most likely to notice?
   A) A range check
   B) A stuck-value check or a cross-check with another sensor
   C) A rate-of-change check
   D) Converting to physical units

4. What is the weakness of a plausibility check that always compares against the last good value?
   A) It uses too much memory
   B) It cannot detect spikes
   C) It only works with integers
   D) After a genuine large jump it may reject every new reading forever unless it has a way to recover

5. Why is the freshness check run every loop rather than only when a new reading arrives?
   A) Because a sensor that stops sending produces no new readings, so a check that waits for one would never run
   B) To make the robot faster
   C) Because readings arrive every loop anyway
   D) To save power

**Go further:**

- Fail-safe — Wikipedia: https://en.wikipedia.org/wiki/Fail-safe — The engineering idea of designing failures so they lead to a safe state.
- Watchdog timer — Wikipedia: https://en.wikipedia.org/wiki/Watchdog_timer — A hardware timer that resets a processor if its software stops responding, a common companion to the checks in this lesson.


---

# Module 5: Embedded communication

How microcontrollers exchange data with sensors, with each other and with larger computers using serial protocols.

**Objectives**

- Compare UART, I²C and SPI in wiring, speed and typical use.
- Explain the purpose of a clock signal and of device addresses on a shared bus.
- Describe how data is framed into bytes and packets.
- Identify why timestamps matter when combining data from several devices.


## 5.1 Serial communication and UART

*How two devices exchange bytes over a single wire each way: baud rate, start and stop bits, parity, and the timing that holds it all together.* (about 25 min)

### Why devices need to talk

A robot is rarely one chip. A microcontroller reads sensors and drives motors; a single-board computer runs vision; a GPS module, a motor driver or a wireless radio each have their own processor. They all need to exchange data, and the simplest, oldest and still most common way is **serial communication**: sending bits one after another down a wire.

Serial is also how you will debug almost everything. The "print a message to the computer" technique from the debugging lesson usually travels over a serial link. Understanding it means understanding the messages you rely on.

### Serial versus parallel

You could send a byte over eight wires at once, one per bit. That is **parallel** communication, and it was common inside older computers. But eight wires (plus ground and control lines) take space, connector pins and cost, and at high speeds the bits on different wires arrive at slightly different times. Sending the bits **one at a time** on a single wire is simpler and, with good timing, fast enough for most embedded tasks.

### UART: serial without a clock wire

A **UART** (universal asynchronous receiver-transmitter) is a peripheral built into almost every microcontroller. It sends bytes on a transmit pin (TX) and receives them on a receive pin (RX). A two-way link needs just three wires:

- device A's TX to device B's RX,
- device B's TX to device A's RX,
- and a **shared ground**, so both agree on what 0 V means.

Crossing TX to RX is the single most common wiring mistake: connect TX to TX and nothing works.

"Asynchronous" means there is **no shared clock signal**. Instead, both sides agree in advance how long each bit lasts. That agreed speed is the **baud rate**, the number of symbols (signal elements) sent per second; for a basic UART each symbol is one bit, so it equals bits per second. Common values are 9600 and 115200 baud. At 9600 baud each bit lasts 1 / 9600 s ≈ 104.17 µs; at 115200 baud, about 8.68 µs.

### The frame: start, data, stop

When nothing is being sent, the line sits **high** (logic 1); this is called **idle**. To send a byte, the UART transmits a **frame**:

1. **Start bit**: the line goes low for one bit time. This falling edge tells the receiver "a byte is starting now" and lets it synchronise its timing.
2. **Data bits**: usually 8, sent **least significant bit first**.
3. Optional **parity bit**, a simple error check (more below).
4. **Stop bit**: the line returns high for at least one bit time, ready for the next start bit.

The most common setting is written **8N1**: 8 data bits, no parity, 1 stop bit. Each byte therefore takes 10 bit times: 1 start + 8 data + 1 stop.

Let us encode the letter "A", which is 0x41 or binary 0100 0001:

```python
def uart_frame(byte, parity=None):
    """Return the line levels for one UART frame, in the order they are sent."""
    bits = [0]                                     # start bit (line pulled low)
    data = [(byte >> i) & 1 for i in range(8)]     # least significant bit first
    bits += data
    if parity == "even":
        bits.append(sum(data) % 2)                 # makes the count of 1s even
    bits.append(1)                                 # stop bit (back to idle high)
    return bits

print("A  8N1:", uart_frame(ord("A")))
print("A  8E1:", uart_frame(ord("A"), parity="even"))
print("C  8E1:", uart_frame(ord("C"), parity="even"))

for baud in [9600, 115200]:
    bit_us = 1e6 / baud
    print(f"{baud:6d} baud: {bit_us:6.2f} us per bit, {baud // 10:5d} bytes per second")
```

Output:

```
A  8N1: [0, 1, 0, 0, 0, 0, 0, 1, 0, 1]
A  8E1: [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1]
C  8E1: [0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1]
  9600 baud: 104.17 us per bit,   960 bytes per second
115200 baud:   8.68 us per bit, 11520 bytes per second
```

("us" stands for microseconds.) Read the first line from left to right as it travels down the wire: a 0 start bit, then the bits of 0x41 starting from the lowest (1, 0, 0, 0, 0, 0, 1, 0), then a 1 stop bit.

Notice the throughput: because each byte costs 10 bits, 115200 baud carries at most 11,520 bytes per second, not 14,400. Framing overhead is the price of not needing a clock wire.

### Parity: a one-bit error check

With **even parity**, the transmitter adds a bit that makes the total number of 1s in the data plus parity even. "A" has two 1s, so its parity bit is 0; "C" (0x43) has three 1s, so its parity bit is 1. If noise flips any single bit, the count becomes odd and the receiver knows the byte is damaged. But if *two* bits flip, the count is even again and the error slips through. Parity is a weak check, which is why the lesson on protocols adds stronger checksums at the message level.

### Timing is everything

With no clock wire, the receiver times each bit with its own clock. After the start bit's falling edge, it waits half a bit time and then samples in the **middle** of each bit. By the stop bit it has counted about nine and a half bit times, so if the two sides' clocks disagree, the sampling point slides towards the edge of the bit.

As a rough guide, if the sampling point drifts by more than about half a bit over those nine and a half bits, the byte is corrupted. That allows only around 5 % total disagreement between the two ends, so each side should be within a couple of percent. This matters because a microcontroller produces its baud rate by dividing its own clock by a whole number, and the division is not always exact. For example, a 16 MHz clock divided by 16 and then by 9 gives 111,111 baud when you asked for 115200, an error of about −3.5 %, which is risky. Datasheets publish tables of baud-rate errors for this reason. Mismatched baud rates show up as garbage characters, a classic symptom to recognise.

### Voltage levels

A microcontroller UART uses its own logic levels, typically 0 V and 3.3 V or 0 V and 5 V. Connecting a 5 V output to a 3.3 V input can damage some chips, so check whether pins are tolerant or use a level shifter. The old **RS-232** standard found on some industrial equipment uses much larger voltages, often around ±12 V, and inverted logic. Never connect RS-232 directly to a microcontroller pin; it needs a converter chip. A USB-to-serial adapter at the correct logic level is the usual way to connect a microcontroller to a computer.

### Recap

A UART sends bytes one bit at a time with no clock wire, so both ends must agree on the baud rate. Each 8N1 frame is a low start bit, eight data bits least-significant first, and a high stop bit: 10 bit times per byte. Parity catches single-bit errors but not double ones. Baud-rate mismatches of more than a few percent corrupt data, and voltage levels must match. Cross TX to RX, and always share ground.

#### Project: Paper project: decode a serial waveform

On squared paper, draw the line level (high or low) against time for the two characters "Hi" sent as 8N1, one after the other, with one square per bit time. "H" is 0x48 and "i" is 0x69.

1. Label the start, data and stop bits of each frame.
2. Add an even-parity bit to each frame and redraw. Which character's parity bit is 1?
3. Swap with a friend: each draws a mystery byte (8N1), and the other decodes it to hexadecimal and, if it is a printable character, to a letter.
4. Calculate how long the two-character message takes at 9600 baud and at 115200 baud.

You can check your drawings with the `uart_frame` Python function. No hardware is needed.

**Deliverables**

- Labelled waveforms for 'Hi' with and without parity
- A decoded mystery byte
- Transmission times at both baud rates, with working

#### Check your understanding

1. How many bit times does one byte take with 8N1 framing?
   A) 8
   B) 9
   C) 10
   D) 11

2. Roughly how many bytes per second can a UART carry at 57600 baud with 8N1 framing?
   A) 5760
   B) 7200
   C) 57600
   D) 576

3. Two boards are wired TX to TX and RX to RX, with a shared ground. What happens?
   A) It works, but at half speed
   B) Nothing is received: each transmitter must connect to the other side's receiver
   C) The baud rate doubles
   D) Only parity bits get through

4. With even parity, which data byte gets a parity bit of 1?
   A) 0x03 (two 1s)
   B) 0x0F (four 1s)
   C) 0x00 (no 1s)
   D) 0x07 (three 1s)

5. A terminal shows random garbage characters when your board sends text. What is the most likely cause?
   A) The two ends are set to different baud rates
   B) The message is too short
   C) The ground wire is too thick
   D) The text uses capital letters

**Go further:**

- Universal asynchronous receiver-transmitter — Wikipedia: https://en.wikipedia.org/wiki/Universal_asynchronous_receiver-transmitter — Frame formats, history and the hardware inside a UART.


## 5.2 I2C: many devices on two wires

*How I2C lets one microcontroller talk to many sensors over a shared two-wire bus: addresses, open-drain lines and pull-ups, acknowledgements, and reading a register.* (about 30 min)

### Many sensors, few pins

A small robot might have a motion sensor, a temperature sensor, a distance sensor and a little display. Giving each one its own UART would use up a microcontroller's pins quickly. **I2C** (pronounced "I-squared-C", short for inter-integrated circuit) solves this: many devices share the same **two wires**, and each has an **address**.

I2C is everywhere in hobby and professional electronics, especially for sensors. Understanding how it works will help you read datasheets and, more often, work out why a sensor is not answering.

### Two wires and a controller

The two signals are:

- **SCL** (serial clock): generated by the **controller**, usually the microcontroller.
- **SDA** (serial data): carries bits in both directions, one way at a time.

The other devices are called **targets** (older documents say master and slave; newer ones use controller and target). Unlike a UART, I2C is **synchronous**: the controller supplies a clock, so both sides know exactly when to read each bit and the clocks do not need to agree in advance. Common speeds are 100 kbit/s (standard mode) and 400 kbit/s (fast mode), with faster modes on some devices.

All devices also share ground and, usually, a supply voltage.

### Open-drain lines and pull-up resistors

Here is the clever part that makes sharing safe. No device ever drives an I2C line *high*. Each device can only pull a line **low** (connect it to ground) or let go of it. A **pull-up resistor** on each line gently pulls it high whenever nobody is pulling it low. This is called an **open-drain** (or open-collector) connection.

Why bother? If two devices drove the same wire, one high and one low, they would fight, and a large current could flow between them. With open-drain lines, the worst case is that the line is low, which is harmless. It also lets any device hold the line low to signal something, which I2C uses for acknowledgements and for **clock stretching**, where a slow target holds SCL low to ask the controller to wait.

Pull-up values of a few kilohms are typical; many boards use something between 2.2 kΩ and 10 kΩ. Too large a resistance and the lines rise slowly, especially with long wires that add capacitance; too small and devices must sink more current when pulling low. Many sensor breakout boards already include pull-ups, and several boards on one bus put several resistors in parallel, so check what is fitted. **Missing pull-ups** are one of the most common reasons an I2C bus does nothing at all.

### How a transfer works

Normally SDA changes only while SCL is low and stays steady while SCL is high. Two special patterns break that rule on purpose:

- **START**: SDA falls while SCL is high. "Everyone listen, a transfer is beginning."
- **STOP**: SDA rises while SCL is high. "The transfer is over; the bus is free."

After a START, the controller sends an **address byte**: the target's 7-bit address followed by one bit saying whether it wants to write (0) or read (1). Every byte on I2C is followed by a ninth clock pulse for the **acknowledge** bit: the receiver pulls SDA low (ACK) to say "got it", or leaves it high (NACK). If no device has that address, nobody pulls SDA low, the controller sees a NACK, and your code learns that the device is absent, unpowered or wired wrongly.

### Address arithmetic

Suppose a sensor's datasheet gives the 7-bit address 0x48. (This is an **example address** for this lesson; always use the value in your own device's datasheet.) The address byte is the address shifted left by one bit, with the read/write bit in the lowest place:

```
write: (0x48 << 1) | 0 = 0x90
read:  (0x48 << 1) | 1 = 0x91
```

Some datasheets and libraries quote the 7-bit address (0x48), others the 8-bit byte (0x90). Mixing these up is a classic bug: if a device "should be at 0x90" but your library wants 7-bit addresses, use 0x48.

### Reading a register

Most I2C sensors present their data as numbered **registers**, like small mailboxes inside the chip. One register might hold a measurement, another a configuration setting. Reading a register usually goes like this:

1. START, then the address byte with write (0x90 in our example). Target ACKs.
2. Send the **register number** you want. Target ACKs.
3. **Repeated START** (a START without a STOP first, so no other controller can grab the bus), then the address byte with read (0x91). Target ACKs.
4. The target sends data bytes. The controller ACKs each one except the last, which it NACKs to say "that's enough".
5. STOP.

In firmware you rarely toggle the pins yourself; your board's library provides a function for the whole sequence. The code below uses a generic stand-in called `i2c_write_read`. Its name and arguments are illustrative, not from any particular library, and the device, address and register are made up for this lesson.

```c
#include <stdint.h>

/* Stand-in for your board's I2C library: write wlen bytes, then a repeated
   start, then read rlen bytes. Returns 0 on success, nonzero on NACK/error. */
int i2c_write_read(uint8_t addr7, const uint8_t *wbuf, int wlen, uint8_t *rbuf, int rlen);

#define EXAMPLE_SENSOR_ADDR  0x48   /* example address only: check your datasheet */
#define EXAMPLE_TEMP_REG     0x05   /* made-up register for this lesson          */

/* Reads temperature in hundredths of a degree. Returns 0 on success. */
int read_temperature_cdeg(int16_t *out)
{
    uint8_t reg = EXAMPLE_TEMP_REG;
    uint8_t buf[2];
    if (i2c_write_read(EXAMPLE_SENSOR_ADDR, &reg, 1, buf, 2) != 0) {
        return -1;                       /* no ACK: wrong address, wiring, power */
    }
    *out = (int16_t)(((uint16_t)buf[0] << 8) | buf[1]);   /* high byte first */
    return 0;
}
```

Suppose our made-up sensor stores temperature as a signed 16-bit number in hundredths of a degree, high byte first. If the two bytes are 0x09 and 0xC4, the value is 0x09C4 = 2500, meaning 25.00 °C. If they are 0xFE and 0x0C, the 16-bit pattern 0xFE0C read as a signed two's-complement number is −500, meaning −5.00 °C. The byte order, signedness and scaling all come from the datasheet, and getting any one wrong produces plausible-looking nonsense. Notice that the function returns an error code: as the reliable-pipelines lesson argued, a failed read must never quietly become a temperature.

### How long does it take?

Each byte costs 9 clock pulses (8 bits plus ACK). The register read above moves 5 bytes (address, register, address, two data bytes), about 45 clock pulses, plus START and STOP. At 100 kHz that is about 450 µs; at 400 kHz about 112.5 µs. Fast enough for a few hundred readings per second from a handful of sensors, but not for streaming large amounts of data.

### Common problems

- **Address conflicts**: two identical sensors share the same address. Many devices offer an address-select pin to change one or two address bits; otherwise you need separate buses or a multiplexer chip.
- **A stuck bus**: if the controller resets in the middle of a transfer, a target may be left holding SDA low. Firmware often recovers by toggling SCL several times until SDA is released.
- **Long wires**: I2C was designed for connections on a single circuit board. Over long cables, capacitance slows the edges and noise creeps in.
- **Scanning**: a simple diagnostic is to try every address and list those that ACK. If your sensor does not appear, check power, ground, pull-ups and wiring before touching your code.

### Recap

I2C shares two wires, SCL and SDA, among many devices, each with its own address. Open-drain outputs and pull-up resistors make sharing safe. Each transfer starts with START and an address byte, every byte is acknowledged, and a register read writes the register number then uses a repeated START to read data back. Check whether addresses are quoted as 7-bit or 8-bit, follow the datasheet for byte order and scaling, and always handle a NACK as a real error.

> **Check voltages before you connect.** I2C devices run at particular supply and logic voltages, often 3.3 V or 5 V, and pull-up resistors must go to a voltage every device on the bus can tolerate. Check each datasheet before wiring. If you experiment with real sensors, use only low-voltage supplies such as USB or small batteries, power off before changing wiring, and work with an adult supervising.

#### Check your understanding

1. A target's 7-bit address is 0x3C. What address byte does the controller send to read from it?
   A) 0x3C
   B) 0x3D
   C) 0x78
   D) 0x79

2. Why do I2C lines need pull-up resistors?
   A) Devices only ever pull lines low, so something must return the lines high when nobody is pulling
   B) To make the bus run faster than SPI
   C) To protect against reversed batteries
   D) To set each device's address

3. After sending an address byte, the controller sees a NACK. What does this most likely mean?
   A) The data was received perfectly
   B) No device responded at that address: it is missing, unpowered, wired wrongly or at a different address
   C) The baud rate is wrong
   D) The target is sending data

4. A sensor returns the bytes 0xFF and 0x9C, high byte first, as a signed 16-bit value in hundredths of a degree. What temperature is this?
   A) 655.32 °C
   B) −0.01 °C
   C) −1.00 °C
   D) 99.00 °C

5. Why does a register read use a repeated START instead of a STOP followed by a new START?
   A) It keeps control of the bus between writing the register number and reading the data
   B) It doubles the clock speed
   C) STOP conditions are not allowed in I2C
   D) It changes the target's address

**Go further:**

- I²C — Wikipedia: https://en.wikipedia.org/wiki/I%C2%B2C — Timing diagrams, speed modes, addressing and clock stretching in more detail.


## 5.3 SPI: fast transfers with chip select

*How SPI moves data quickly using a clock, two data lines and a chip-select per device, how its shift-register exchange works, and when to choose it over I2C.* (about 25 min)

### When I2C is not fast enough

I2C is wonderfully economical with wires, but it tops out at a few hundred kilobits per second for most devices, and each byte carries an acknowledgement. Some devices need much more: a small display that redraws thousands of pixels, a memory card storing a data log, or a fast ADC sampling thousands of times per second. For these, engineers reach for **SPI**, the serial peripheral interface.

### Four signals

SPI usually uses four wires, plus ground:

- **SCLK** (serial clock): driven by the controller.
- **MOSI** (controller out, peripheral in): data from controller to device. Newer documents call it **COPI** or **SDO** on the controller.
- **MISO** (controller in, peripheral out): data from device to controller, also called **CIPO**.
- **CS** (chip select, sometimes SS or CE): one per device, usually **active low**, meaning the device listens only while its CS line is held low.

Like I2C, SPI is **synchronous**, with the controller providing the clock. Unlike I2C, its outputs are **driven** high and low (push-pull) rather than pulled up, so edges are sharp and speeds of several megahertz, sometimes tens of megahertz, are common over short connections.

### No addresses: chip select instead

SPI has no address bytes. To talk to a particular device, the controller pulls *that* device's CS line low; every other device, with CS high, ignores the clock and leaves MISO alone. Three devices need three CS pins, but share SCLK, MOSI and MISO.

That trade is the heart of SPI. You spend extra pins, and in return you get no address overhead, no acknowledgement bits and no pull-up resistors limiting speed.

### The shift-register exchange

SPI is built on a neat idea. The controller and the device each have an 8-bit **shift register**, and the two are connected in a ring: MOSI carries bits from the controller's register into the device's, and MISO carries bits from the device's into the controller's. On each clock pulse, both shift by one bit. After eight clocks, the two bytes have **swapped places**.

This means SPI is **full duplex**: every transfer sends a byte and receives a byte at the same time. Here is a simulation, most significant bit first:

```python
def spi_exchange(controller_byte, peripheral_byte):
    """Simulate one 8-bit SPI transfer, most significant bit first."""
    c, p = controller_byte, peripheral_byte
    for clock in range(8):
        mosi = (c >> 7) & 1          # controller puts its top bit on MOSI
        miso = (p >> 7) & 1          # peripheral puts its top bit on MISO
        c = ((c << 1) & 0xFF) | miso # each side shifts in the other's bit
        p = ((p << 1) & 0xFF) | mosi
        print(f"clock {clock}: MOSI={mosi} MISO={miso}  "
              f"controller={c:08b} peripheral={p:08b}")
    return c, p

got_c, got_p = spi_exchange(0xA5, 0x3C)
print(f"controller received 0x{got_c:02X}, peripheral received 0x{got_p:02X}")
```

Output:

```
clock 0: MOSI=1 MISO=0  controller=01001010 peripheral=01111001
clock 1: MOSI=0 MISO=0  controller=10010100 peripheral=11110010
clock 2: MOSI=1 MISO=1  controller=00101001 peripheral=11100101
clock 3: MOSI=0 MISO=1  controller=01010011 peripheral=11001010
clock 4: MOSI=0 MISO=1  controller=10100111 peripheral=10010100
clock 5: MOSI=1 MISO=1  controller=01001111 peripheral=00101001
clock 6: MOSI=0 MISO=0  controller=10011110 peripheral=01010010
clock 7: MOSI=1 MISO=0  controller=00111100 peripheral=10100101
controller received 0x3C, peripheral received 0xA5
```

Watch the bits of 0xA5 (10100101) march into the peripheral one at a time while 0x3C (00111100) marches the other way.

A consequence surprises many beginners: **to read from an SPI device, you must send something.** The controller only produces clock pulses while it is transmitting, so to receive a byte it sends a dummy byte (often 0x00 or 0xFF) purely to drive the clock.

### A typical register read

Many SPI sensors use a register scheme similar to I2C devices, sent as a sequence of bytes while CS is held low. A common pattern (check your datasheet: details vary between devices) is:

1. Pull CS low.
2. Send a command byte containing the register number, often with one bit set to mean "read".
3. Send dummy bytes; the device's data arrives on MISO during them.
4. Pull CS high to end the transaction.

In illustrative firmware, using a generic stand-in `spi_transfer(byte)` that sends one byte and returns the byte received, and `gpio_write(pin, level)` for the CS pin:

```c
uint8_t read_register(uint8_t reg)
{
    gpio_write(EXAMPLE_CS_PIN, 0);        /* select the device          */
    spi_transfer(reg | EXAMPLE_READ_BIT); /* command: "read this register" */
    uint8_t value = spi_transfer(0x00);   /* dummy byte clocks data in   */
    gpio_write(EXAMPLE_CS_PIN, 1);        /* deselect                    */
    return value;
}
```

These names and the read-bit convention are placeholders for this lesson; your board's library and your device's datasheet define the real ones.

### SPI modes

Devices disagree about two details: whether the clock idles low or high (**CPOL**, clock polarity), and whether data is sampled on the first or second clock edge of each bit (**CPHA**, clock phase). The four combinations are called **modes 0 to 3**. Mode 0 (clock idles low, data sampled on the rising edge) is very common, but not universal. If an SPI device returns data that is shifted by a bit or consistently garbled, a wrong mode is a prime suspect. The datasheet will state the mode, sometimes only as a timing diagram.

### Speed comparison

At 1 MHz, one SPI byte takes 8 µs. At 400 kHz, one I2C byte takes 9 clock pulses, about 22.5 µs, before counting START, STOP and addressing. And SPI can often run at 8 MHz or more, where a byte takes just 1 µs. For bulk data the gap is large.

### Choosing between SPI and I2C

- **Choose I2C** when you have several slow-to-moderate sensors, few spare pins and short connections. Two wires serve them all.
- **Choose SPI** when you need speed or large transfers (displays, memory cards, fast ADCs), full-duplex streaming, or simpler timing with no acknowledgements.
- **Pins**: I2C uses 2 regardless of device count; SPI uses 3 shared plus 1 CS per device.
- **Error detection**: I2C at least tells you when nobody answers (NACK). SPI gives no such signal: if a device is unplugged, MISO may simply read as all 0s or all 1s. Robust SPI code checks identity registers or data plausibility.
- **Distance**: both are meant for short connections on or between nearby boards, not for long cables.

### Recap

SPI uses a clock, two one-way data lines and a chip-select line per device. Selecting a device by pulling its CS low replaces addressing, and the shift-register ring means every transfer sends and receives at once, so reading requires sending dummy bytes. Clock polarity and phase must match the device's mode. SPI is faster and simpler per byte than I2C but uses more pins and gives no built-in acknowledgement.

> **Unplugged does not mean silent.** With nothing driving MISO, an SPI read may return 0x00 or 0xFF every time, depending on the circuit. Many devices have a fixed identity register with a known value given in the datasheet. Reading it at start-up and comparing with the expected value is a cheap way to confirm the device is really there.

#### Project: Python project: simulate an SPI device

Extend the `spi_exchange` simulation into a pretend SPI sensor.

1. Create a Python class with a few made-up registers stored in a list, for example register 0x00 holding a fixed identity value of your choice.
2. Write a `transaction(bytes_out)` method that behaves like a device with CS held low: the first byte received is a command (top bit set means read, lower 7 bits are the register number), and on following bytes the device returns the register contents.
3. Write a "controller" function that reads the identity register and checks it, then reads a register holding a made-up measurement.
4. Simulate an unplugged device that returns 0xFF for every byte, and show that your identity check catches it.

This is a simulation only. No hardware is needed.

**Deliverables**

- Python code for the simulated device and controller
- Output showing a successful identity check and a measurement read
- Output showing the unplugged case being detected

#### Check your understanding

1. How does an SPI controller choose which of several devices to talk to?
   A) By sending a 7-bit address first
   B) By changing the clock speed
   C) By pulling that device's own chip-select line low
   D) By waiting for the device to acknowledge

2. Why must the controller send a byte in order to read one from an SPI device?
   A) The controller only generates clock pulses while shifting data out, and the device's data moves only on those pulses
   B) SPI devices refuse to answer unless thanked
   C) To calculate a checksum
   D) Because MISO and MOSI are the same wire

3. A design has five SPI devices. How many signal wires does the SPI bus need, not counting power and ground?
   A) 4
   B) 5
   C) 20
   D) 8

4. An SPI device returns data that looks shifted by one bit. What is the most likely cause?
   A) Missing pull-up resistors
   B) The controller is using the wrong SPI mode (clock polarity or phase)
   C) The I2C address is wrong
   D) The baud rate is mismatched

5. Which job is SPI generally better suited to than I2C?
   A) Reading five slow temperature sensors with only two spare pins
   B) Connecting devices across a large building
   C) Sending a full frame of pixels to a small display quickly
   D) Detecting automatically that a device has no address

**Go further:**

- Serial Peripheral Interface — Wikipedia: https://en.wikipedia.org/wiki/Serial_Peripheral_Interface — Timing diagrams for the four SPI modes and variations such as daisy-chaining.


## 5.4 Designing a message protocol

*Turning a stream of bytes into reliable messages: start markers, length fields, checksums and CRCs, byte order and version numbers, with a working parser.* (about 35 min)

### Bytes are not messages

A UART delivers bytes. It does not tell you where one message ends and the next begins, whether a byte was lost, or whether noise flipped a bit. Suppose a microcontroller sends distance readings to a single-board computer as the text "1234\n". It works on the bench. Then a motor starts, a burst of interference corrupts a character, and the computer reads "1294". Nothing in that text says it is wrong.

A **message protocol** is the set of rules both sides agree on for packaging data so the receiver can find messages, check them, and reject the damaged ones. Designing one well is a core embedded skill, and the same ideas appear in every network protocol you will ever use.

### The parts of a frame

A typical binary frame looks like this:

```
| START | VERSION | TYPE | LENGTH | PAYLOAD (LENGTH bytes) | CRC (2 bytes) |
```

- **Start marker**: a fixed byte, such as 0xAA, that says "a frame might begin here". It lets a receiver that joins mid-stream, or loses a byte, find its place again.
- **Version**: which edition of the protocol this frame follows, so you can change the format later without confusing old devices.
- **Type**: what kind of message this is: a distance reading, a motor command, an error report.
- **Length**: how many payload bytes follow. The receiver knows exactly where the frame ends without needing a special terminator.
- **Payload**: the data itself.
- **Check value**: a checksum or CRC calculated from the other bytes, so the receiver can detect corruption.

### Packing numbers: byte order

A 16-bit number such as 1234 (0x04D2) occupies two bytes, and the two sides must agree on their order. **Little-endian** sends the low byte first (D2 04); **big-endian** sends the high byte first (04 D2). Neither is "right", but mixing them up turns 1234 into 53764. Write the byte order into the protocol's documentation. Python's standard `struct` module packs and unpacks values with an explicit order: `"<"` means little-endian, `"H"` an unsigned 16-bit value and `"I"` an unsigned 32-bit value.

### Checksums and CRCs

The simplest check value is a **sum**: add all the bytes and keep the low 8 bits. It catches many single-byte errors but has blind spots. Since addition does not care about order, swapping two bytes gives the same sum.

A **cyclic redundancy check** (CRC) is a stronger, still cheap, calculation based on polynomial division of the data's bits. A 16-bit CRC detects every single-bit and double-bit error in a message of moderate length, every burst error up to 16 bits long (which includes two neighbouring bytes swapped). Python's standard library includes a common 16-bit CRC as `binascii.crc_hqx`:

```python
import struct
import binascii

START = 0xAA
VERSION = 1
MSG_DISTANCE = 0x10

def checksum8(data):
    """Simple checksum: sum of all bytes, keeping only the low 8 bits."""
    return sum(data) & 0xFF

def crc16(data):
    """CRC-16/CCITT-FALSE from the standard library."""
    return binascii.crc_hqx(data, 0xFFFF)

def build_frame(msg_type, payload):
    body = bytes([VERSION, msg_type, len(payload)]) + payload
    return bytes([START]) + body + struct.pack("<H", crc16(body))

# Payload: distance in millimetres (uint16) and a timestamp in ms (uint32),
# both little-endian.
payload = struct.pack("<HI", 1234, 56789)
frame = build_frame(MSG_DISTANCE, payload)
print("frame:", frame.hex(" "))

# A swap of two payload bytes fools the simple sum, but not the CRC.
good = bytes([0x01, 0x02, 0x03])
swapped = bytes([0x02, 0x01, 0x03])
print("sum  :", hex(checksum8(good)), hex(checksum8(swapped)))
print("crc16:", hex(crc16(good)), hex(crc16(swapped)))
print("check value:", hex(crc16(b"123456789")))
```

Output:

```
frame: aa 01 10 06 d2 04 d5 dd 00 00 b1 fa
sum  : 0x6 0x6
crc16: 0xadad 0xa1ae
check value: 0x29b1
```

Read the frame byte by byte: start 0xAA, version 1, type 0x10, length 6, then 1234 as d2 04, then 56789 (0x0000DDD5) as d5 dd 00 00, then the CRC 0xFAB1 sent low byte first. The last line is a useful habit: CRCs come in many variants, and each has a published **check value**, its result for the ASCII text "123456789". If your C implementation on the microcontroller gives 0x29B1 for that string too, both sides are computing the same CRC.

Note that a CRC detects *accidental* errors. It is not security: anyone can compute a valid CRC for a forged message. Protecting against deliberate tampering needs cryptographic authentication, a topic of its own.

### Writing a receiver that resynchronises

The receiver is where the design pays off. It scans for the start byte, reads the header, checks that the version and length are sensible, waits for the whole frame, and verifies the CRC. If anything fails, it moves forward **one byte** and searches again, because the 0xAA it found might have been an ordinary data byte rather than a real start.

```python
MAX_PAYLOAD = 32

def parse_stream(stream):
    """Yield (msg_type, payload) for every valid frame found in a byte stream."""
    i = 0
    while i < len(stream):
        if stream[i] != START:
            i += 1                       # not a frame start: skip one byte
            continue
        if i + 4 > len(stream):
            break                        # header incomplete: wait for more bytes
        version, msg_type, length = stream[i + 1], stream[i + 2], stream[i + 3]
        end = i + 4 + length + 2
        if version != VERSION or length > MAX_PAYLOAD:
            i += 1                       # implausible header: resynchronise
            continue
        if end > len(stream):
            break
        body = stream[i + 1: i + 4 + length]
        (received,) = struct.unpack("<H", stream[end - 2: end])
        if crc16(body) == received:
            yield msg_type, body[3:]
            i = end
        else:
            print(f"bad CRC in frame at byte {i}, skipping")
            i += 1

a = build_frame(0x10, struct.pack("<HI", 1234, 56789))
b = bytearray(build_frame(0x10, struct.pack("<HI", 1240, 56889)))
b[5] ^= 0x04                             # flip one bit "in transit"
c = build_frame(0x10, struct.pack("<HI", 1251, 56989))
stream = bytes([0x37, 0xAA, 0x99]) + a + bytes(b) + c

for msg_type, payload in parse_stream(stream):
    mm, ms = struct.unpack("<HI", payload)
    print(f"type 0x{msg_type:02X}: {mm} mm at t = {ms} ms")
```

Run this after the code above (it reuses `START`, `VERSION`, `crc16`, `build_frame` and `struct`). This part prints:

```
type 0x10: 1234 mm at t = 56789 ms
bad CRC in frame at byte 15, skipping
type 0x10: 1251 mm at t = 56989 ms
```

The stream starts with junk, including a stray 0xAA that is rejected because the next byte is not a valid version. The first real frame is decoded. The second has one flipped bit, so its CRC fails and it is dropped rather than delivered as a wrong distance. The receiver then finds the third frame. In firmware, the same logic is usually written as a **state machine** that processes one byte at a time as each arrives from the UART, which you met in the programming-foundations module.

### Design decisions worth making early

- **Maximum length**: cap the payload size so a corrupted length byte cannot make the receiver wait for thousands of bytes.
- **Versioning**: put a version field in from day one. Adding it later is much harder than ignoring it now.
- **Units and scaling**: send integers in documented units (millimetres, milliseconds) rather than floats, as in the fixed-point lesson.
- **Timestamps**: include the time each measurement was taken, not when it was sent.
- **Sequence numbers**: a counter that increases with each frame lets the receiver detect lost frames.
- **What happens on error**: decide whether the receiver silently drops, logs, or asks for a resend. For commands that move motors, a dropped frame is usually safer than a guessed one.
- **Byte stuffing**: an alternative to length fields is to reserve the start byte and escape it wherever it appears in data. Schemes such as COBS (consistent overhead byte stuffing) do this efficiently.

### Recap

A protocol turns a byte stream into checkable messages. A start marker lets the receiver find frames, a length field says where they end, a version field allows change, and a CRC detects corruption far better than a simple sum. Document byte order and units, cap the payload length, and write a receiver that resynchronises by stepping forward one byte when anything is wrong. A damaged message should be dropped, never delivered.

> **Write the protocol down.** A protocol lives in two programs, often in two languages, sometimes written by two people. Keep a short document listing every field, its size, byte order, units, valid range and the CRC variant with its check value. Update the version number whenever the format changes. The document is what keeps both ends honest.

#### Project: Python project: design and break your own protocol

1. Design a frame for a small robot that sends three values: a battery voltage in millivolts, a motor speed in revolutions per minute (which can be negative), and a status byte. Write a one-page specification listing every field, with its size, byte order, units and range.
2. Implement `build_frame` and a resynchronising `parse_stream` for it in Python, using `struct` and `binascii.crc_hqx`.
3. Write a test that builds 100 frames, then corrupts the stream in several ways: flip random bits, delete a byte, insert junk, swap two bytes. Use `random.seed(1)` so your results repeat. Count how many frames are decoded correctly, how many are rejected, and confirm none are decoded *wrongly*.
4. Repeat with the simple 8-bit sum instead of the CRC and compare.

This is a computer-only activity. No hardware is needed.

**Deliverables**

- A written frame specification
- Python builder, parser and corruption tests
- Counts of good, rejected and wrongly accepted frames for the CRC and the simple sum

**Safety (adult supervision required):** This is a software-only project; the battery and motor values are invented numbers. If you later send these frames from real hardware, use only low-voltage, battery-powered boards, keep any motors small and secured, and work with an adult supervising.

#### Check your understanding

1. What is the main job of the length field in a frame?
   A) It tells the receiver exactly how many payload bytes to expect, so it knows where the frame ends
   B) It encrypts the payload
   C) It sets the baud rate
   D) It replaces the need for a checksum

2. The value 0x1234 is sent little-endian. In what order do the bytes appear on the wire?
   A) 12 34
   B) 34 12
   C) 21 43
   D) 43 21

3. Why can a simple sum checksum miss an error where two bytes are swapped?
   A) Because the sum is only 4 bits
   B) Because swapped bytes are always caught by parity
   C) Because addition gives the same total in any order
   D) Because the start byte hides the error

4. A parser finds 0xAA, but the CRC check fails. What should it do next?
   A) Deliver the payload anyway, since most of it is probably right
   B) Discard the whole stream and restart the device
   C) Skip to the end of the claimed frame and continue
   D) Move forward one byte and search for the next start marker

5. Why include a version field from the very first design?
   A) It makes frames smaller
   B) So devices can recognise and handle frames from older or newer formats when the protocol changes
   C) It is required by the UART hardware
   D) It improves the CRC

**Go further:**

- struct — Python documentation: https://docs.python.org/3/library/struct.html — Format characters and byte-order prefixes for packing binary data.
- binascii — Python documentation: https://docs.python.org/3/library/binascii.html — Includes crc_hqx and crc32 for computing CRCs.
- Cyclic redundancy check — Wikipedia: https://en.wikipedia.org/wiki/Cyclic_redundancy_check — How CRCs work and which errors they are guaranteed to detect.
- Consistent Overhead Byte Stuffing — Wikipedia: https://en.wikipedia.org/wiki/Consistent_Overhead_Byte_Stuffing — An efficient alternative framing method using byte stuffing.


## 5.5 Wireless options and trade-offs

*Choosing a wireless link for a robot or sensor: range, power, bandwidth, latency and reliability, battery-life estimates, and why safety functions must not depend on radio.* (about 30 min)

### Cutting the cable

Wires are reliable, fast and cheap, so why go wireless? Because some robots move too far or too freely for a cable: a drone, a rover in a field, a sensor strapped to a moving arm, or a swarm of small robots on a table. Wireless links also let you monitor a robot from a laptop without tripping over its tether.

Every wireless link, however, gives up something compared with a wire. The skill is choosing which trade-offs your task can live with, and designing the system so it stays safe when the radio fails, because sooner or later it will.

### The five trade-offs

When comparing wireless options, ask about:

1. **Range**: how far apart can the devices be, indoors and outdoors?
2. **Power**: how much current does the radio draw while transmitting, receiving and sleeping?
3. **Bandwidth**: how much data per second can it carry?
4. **Latency**: how long from "send" to "received"?
5. **Reliability**: how often are messages lost or delayed, and what happens when they are?

These pull against each other. Physics makes it hard to get long range, high bandwidth and low power all at once. Radio signals spread out as they travel: in open space the received power falls with the square of distance, so doubling the distance leaves a quarter of the power. Walls, bodies, metal and water absorb and reflect signals further, so indoor range is usually much shorter than outdoor range.

### A tour of common options

These are broad, typical characteristics. Exact figures depend heavily on the specific module, antenna, settings and environment, so treat them as starting points and test in your real setting.

- **Wi-Fi**: high bandwidth, enough for video, and connects directly to computers and networks. It draws a lot of power compared with the alternatives, and latency can vary, especially on a busy network. Good for a robot with a substantial battery that streams camera images to a laptop.
- **Bluetooth Low Energy (BLE)**: designed for low power and modest data, such as sensor readings or control commands from a phone. Typical indoor ranges are around tens of metres. Good for wearables and small battery-powered sensors.
- **IEEE 802.15.4-based networks** (such as Zigbee and Thread): low power and low data rate, and designed for **mesh networks**, where devices relay each other's messages to extend coverage. Common in home and building sensors.
- **Sub-GHz long-range radios** (such as LoRa): very long range, often kilometres outdoors, at very low power, but with very low data rates and long transmission times. Good for a field sensor that reports a few bytes every few minutes; far too slow for driving a robot.
- **Simple 2.4 GHz or sub-GHz transceiver modules**: small, cheap radios that send short packets with low latency, often used in hobby remote controls. You usually design the protocol yourself, using the ideas from the previous lesson.

Many of these share the crowded 2.4 GHz band, so Wi-Fi, Bluetooth and others can interfere with each other. Radio use is also **regulated**: each country sets which frequencies may be used and at what power. Using a pre-certified module with its intended antenna and settings is the simplest way to stay within the rules.

### Estimating battery life

Radios save power by sleeping most of the time and waking briefly to transmit. The **average current** decides battery life. Suppose (with made-up but plausible numbers) a sensor's radio draws 20 mA while transmitting for 10 ms, once per second, and 0.01 mA asleep for the remaining 990 ms:

```
average = 20 mA × (10 / 1000) + 0.01 mA × (990 / 1000)
        = 0.2 mA + 0.0099 mA
        ≈ 0.21 mA
```

From a 1000 mAh battery, that is roughly 1000 / 0.21 ≈ 4,760 hours, about 198 days, ignoring the sensor and microcontroller, battery self-discharge and temperature effects. Now send ten times per second instead: the transmit term becomes 2.0 mA, the average about 2.01 mA, and the same battery lasts about 21 days. **How often you transmit usually matters more than which radio you chose.** Sending only when something changes, or batching readings into fewer, larger messages, can multiply battery life.

### Latency and lost messages

On a wire, a message either arrives in a predictable time or something is broken. On a radio link, messages are routinely lost to interference or briefly blocked by a person walking past. Many radios automatically retransmit lost packets, which improves reliability but makes latency unpredictable: a message might take 5 ms or 200 ms.

For control, **late data can be worse than no data**. A steering command that arrives 300 ms late was meant for a situation that no longer exists. A common design gives each command a sequence number and a timestamp, and the robot ignores commands that are too old.

### Safety-critical caveats

A wireless link must never be the only thing standing between a robot and harm.

- **Heartbeats and link-loss timeouts**: the controller sends a small "I'm here" message regularly, for example 10 times a second. If the robot hears nothing for a set time, say 0.5 s, it stops or enters a safe state by itself. This uses the same timeout pattern as the reliable-pipelines lesson. Never design a robot that keeps doing its last command when the link drops.
- **Emergency stops**: a wireless "stop" button is useful, but machines that can hurt people need a physical emergency stop that cuts actuator power directly and does not depend on software or radio.
- **Security**: a link that anyone nearby can send commands to is a hazard. Use pairing and encryption where available, and do not accept movement commands from unauthenticated sources.
- **Test in the real environment**: range on an empty desk is not range in a classroom full of people, phones and laptops.

### Recap

Choose wireless links by range, power, bandwidth, latency and reliability, and accept that you cannot maximise them all. Wi-Fi gives bandwidth at a power cost; BLE and 802.15.4 networks give low power for modest data; long-range sub-GHz radios trade speed for distance. Battery life depends mostly on how often the radio transmits. Expect lost and late messages, reject stale commands, and design the robot to make itself safe on link loss, with a physical emergency stop for anything that could cause harm.

> **Fail safe when the radio goes quiet.** Any robot you build that moves under wireless control must stop by itself if it stops hearing from its controller. Test this on purpose: switch the transmitter off while the robot is moving slowly on the floor and check it stops. Keep experimental robots small and low-voltage, run tests in a clear area away from people, pets, stairs and roads, and work with an adult supervising.

#### Project: Paper project: choose a link and budget its battery

Pick two of these scenarios:

- a soil-moisture sensor in a garden that reports once every 10 minutes,
- a small classroom robot driven from a laptop with a live camera view,
- a wearable motion sensor that streams 50 readings per second to a phone,
- a robot arm on a table that receives occasional position commands.

For each one:

1. Rank range, power, bandwidth, latency and reliability from most to least important, and justify your top two.
2. Choose a wireless option from this lesson (or decide a cable is better) and explain why.
3. Estimate average current and battery life using made-up but plausible transmit, receive and sleep currents, clearly labelled as assumptions.
4. Describe what the system does when the link is lost for 1 second and for 1 minute.

This is a paper activity. No hardware is needed.

**Deliverables**

- A ranked list of trade-offs for each scenario
- A justified wireless choice for each
- Battery-life calculations with assumptions labelled
- A link-loss plan for each

**Safety (adult supervision required):** This project is paper-based. If you later test a real wireless link, use only small, low-voltage battery-powered devices, never charge or puncture damaged batteries, test moving robots slowly in a clear area away from people, and work with an adult supervising.

#### Check your understanding

1. In open space, received radio power falls with the square of distance. If you triple the distance, the received power becomes:
   A) One third
   B) One sixth
   C) One ninth
   D) Three times larger

2. A radio draws 30 mA for 5 ms every second and almost nothing otherwise. What is its approximate average current?
   A) 0.15 mA
   B) 30 mA
   C) 1.5 mA
   D) 6 mA

3. A field sensor must send a few bytes every 15 minutes from 2 km away, on a small battery. Which option fits best?
   A) Wi-Fi
   B) A long-range sub-GHz radio such as LoRa
   C) SPI
   D) Bluetooth Low Energy

4. A wirelessly controlled robot loses its link. What should a well-designed robot do?
   A) Continue its last command until the link returns
   B) Speed up to find a better signal
   C) Wait indefinitely for instructions while moving
   D) Detect the missing heartbeat within a set timeout and stop or enter a safe state

5. Why can late commands be worse than lost ones in a control system?
   A) Late commands use more battery
   B) A late command was meant for a situation that has already changed, so acting on it can be wrong
   C) Late commands always have bad checksums
   D) Radios cannot deliver late messages

**Go further:**

- Bluetooth Low Energy — Wikipedia: https://en.wikipedia.org/wiki/Bluetooth_Low_Energy — How BLE achieves low power, and how it differs from classic Bluetooth.


## 5.6 Timestamps and synchronising devices

*Why every device keeps slightly different time, how clock drift and latency corrupt combined data, and how to estimate clock offsets and align sensor streams.* (about 30 min)

### When did that happen?

A robot arm reaches for an object. A camera on a separate computer spots the object; a force sensor in the gripper, read by a microcontroller, feels the first touch. To fuse these, as in the sensor-fusion lesson, the robot must know *when* each measurement was made. If the camera image is 100 ms old and the arm moves at 0.5 m/s, the object's position is already 5 cm out of date.

Every device in a robot keeps its own time, and no two agree perfectly. This lesson is about measuring and correcting that disagreement so data from different devices can be combined honestly.

### Measurement time, not arrival time

The most important rule: **timestamp a measurement when it is taken, not when it arrives.** Between the two there is **latency**: conversion time in the sensor, waiting in buffers, transmission over a bus or radio, and processing. A camera frame might be exposed at 80 ms, transferred and processed, and reach your code at 120 ms. If you stamp it 120, you have built a 40 ms error into everything downstream.

When the sensor itself cannot stamp its data, measure the typical latency and subtract it, and record that you did so. The fusion explorer in the sensor-integration module notes this as one of its simplifications: its camera has no latency, and real filters must compensate.

### Clocks drift

A microcontroller's sense of time comes from an oscillator, often a quartz crystal. Crystals are good but not perfect, and their accuracy is quoted in **parts per million** (ppm). A clock accurate to 20 ppm may gain or lose up to 20 µs every second:

```
20 ppm × 86,400 s per day = 1.728 s per day
```

That is small for a wristwatch but large for a robot. Worse, two devices can drift in *opposite* directions. If each is within ±50 ppm, they can disagree by up to 100 ppm, which is 0.36 s per hour. Drift also changes with temperature, so you cannot just measure it once. Some cheaper oscillators built into microcontrollers are much less accurate than crystals.

There are three separate problems here:

- **Offset**: two clocks show different times right now (for example, they started counting at different moments).
- **Drift**: they tick at slightly different rates, so the offset changes over time.
- **Latency**: messages take time to travel, so you cannot simply send "the time is now T".

### Estimating offset with a round trip

Here is a neat trick used, in more refined form, by the Network Time Protocol (NTP) that keeps computers' clocks set. Device A sends a request, and four times are recorded:

- t1: A sends the request (A's clock)
- t2: B receives it (B's clock)
- t3: B sends the reply (B's clock)
- t4: A receives the reply (A's clock)

```python
def clock_offset(t1, t2, t3, t4):
    """Offset of the remote clock and round-trip delay, from one exchange.
    t1: request sent (local clock)   t2: request received (remote clock)
    t3: reply sent (remote clock)    t4: reply received (local clock)"""
    delay = (t4 - t1) - (t3 - t2)
    offset = ((t2 - t1) + (t3 - t4)) / 2
    return offset, delay

print(clock_offset(1000, 1254, 1255, 1011))
```

Output:

```
(249.0, 10)
```

All times are in milliseconds. The round trip took 11 ms on A's clock, of which B spent 1 ms preparing the reply, so the messages spent 10 ms travelling. Assuming the trip each way took the same time (5 ms), B's clock is 249 ms ahead of A's. Check: A sent at 1000, so the request arrived at 1005 in A's time, which is 1005 + 249 = 1254 in B's time. It matches.

The key assumption is **symmetric delay**. If the outgoing trip is slower than the return, the offset estimate is wrong by half the difference. Repeating the exchange many times and trusting the ones with the smallest delay reduces this error, because those were least affected by queues. Repeating it regularly also tracks drift.

### Other ways to synchronise

- **A shared trigger wire**: one device pulses a digital line, and every device records its own clock reading at the pulse, often using an interrupt or timer-capture feature. Simple and very accurate for devices on one robot.
- **Hardware-triggered sensors**: many cameras and sensors accept a trigger input, so measurements happen at exactly the moment the controller chooses.
- **Precision Time Protocol (PTP)**: a network standard that, with hardware support, can synchronise clocks across a network far more tightly than NTP.
- **GPS time**: GPS receivers can output a very accurate pulse once per second, useful for outdoor systems far apart.
- **One clock for everything**: when possible, have a single device stamp all the data as it arrives at known, measured latencies.

### Aligning streams

Even with synchronised clocks, sensors sample at different moments and rates. An IMU might report every 10 ms while a camera delivers a frame every 33 ms. To combine them, you need the IMU's value *at the camera frame's time*, which usually falls between two IMU samples. **Linear interpolation** estimates it from the samples on either side. The data below are made up for illustration:

```python
# Made-up gyro angles (degrees), stamped every 10 ms by the same clock.
imu_t = [0, 10, 20, 30, 40, 50, 60, 70]
imu_angle = [0.0, 1.0, 2.1, 3.3, 4.6, 6.0, 7.5, 9.1]

def value_at(t, times, values):
    """Linearly interpolate a value at time t from sorted samples."""
    for i in range(len(times) - 1):
        t0, t1 = times[i], times[i + 1]
        if t0 <= t <= t1:
            fraction = (t - t0) / (t1 - t0)
            return values[i] + fraction * (values[i + 1] - values[i])
    raise ValueError("t is outside the recorded range")

# Camera frames: exposure time, already corrected for the camera's latency.
for frame_t in [13, 46, 63]:
    print(f"frame at {frame_t} ms: gyro angle {value_at(frame_t, imu_t, imu_angle):.2f} deg")
```

Output:

```
frame at 13 ms: gyro angle 1.33 deg
frame at 46 ms: gyro angle 5.44 deg
frame at 63 ms: gyro angle 7.98 deg
```

The frame at 13 ms is 30 % of the way from the 10 ms sample (1.0°) to the 20 ms sample (2.1°), so the estimate is 1.0 + 0.3 × 1.1 = 1.33°. Two cautions: interpolation assumes the signal changes smoothly between samples, which is only reasonable if you sampled fast enough (remember aliasing), and it refuses to extrapolate beyond the data, because guessing the future is a different, riskier job.

### Practical habits

- Stamp every measurement at the source, in a documented unit, ideally milliseconds or microseconds as integers.
- Use the wrap-safe elapsed-time arithmetic from the non-blocking timing lesson, since a 32-bit millisecond counter wraps after about 49.7 days.
- Log the raw timestamps from every device, not only corrected ones, so alignment can be redone later if you find a mistake.
- Measure your latencies rather than guessing, for example by triggering an LED that a camera can see and comparing timestamps.

### Recap

Combine data by when it was measured, not when it arrived. Every clock has an offset and drifts, typically by tens of ppm, and messages add latency. A four-timestamp round trip estimates offset and delay, assuming the delay is symmetric; trigger wires, PTP and GPS give tighter synchronisation. Align streams sampled at different times by interpolating, and keep raw timestamps so your alignment can always be checked.

> **Say how you aligned your data.** When you report results from several sensors, state how their clocks were synchronised, what latencies you corrected for and how you measured them, and how samples were matched or interpolated. Alignment choices can change results, so they belong in your methods, not hidden in code.

#### Project: Python project: drift and alignment

1. Simulate two clocks: one perfect, one running 80 ppm fast with a 300 ms starting offset. Print what each reads after 1 minute, 1 hour and 1 day.
2. Every 10 simulated seconds, perform a round-trip offset estimate with a random one-way delay between 2 and 8 ms in each direction (use `random.seed(2)` so results repeat). Plot or print the estimated offset over time and the error of each estimate.
3. Improve your estimate by doing five exchanges each time and keeping the one with the smallest round-trip delay. Compare the errors.
4. Use `value_at` to align a made-up 100 Hz stream to a made-up 30 Hz stream, and explain what goes wrong if you forget to correct a 40 ms latency.

This is a computer-only activity. No hardware is needed.

**Deliverables**

- Clock readings showing offset and drift growing
- Offset-estimate errors for single exchanges and for best-of-five
- An alignment example with and without latency correction, with a short explanation

#### Check your understanding

1. A clock is accurate to 10 ppm. About how far could it drift in one day?
   A) 10 ms
   B) 0.86 s
   C) 10 s
   D) 86 s

2. Why should a camera frame be stamped with its exposure time rather than its arrival time?
   A) Arrival time is always zero
   B) Exposure time is easier to measure
   C) The delay between exposure and arrival would otherwise become an error in everything that uses the frame
   D) Cameras cannot record arrival time

3. In a round-trip exchange, t1 = 0, t2 = 105, t3 = 106, t4 = 11 (all ms). What is B's clock offset relative to A?
   A) 105 ms
   B) 95 ms
   C) 50 ms
   D) 100 ms

4. What assumption does the round-trip offset estimate rely on?
   A) The outgoing and return trips take the same time
   B) Both clocks are perfectly accurate
   C) The messages contain a CRC
   D) The devices use I2C

5. IMU samples read 2.0° at 20 ms and 3.0° at 30 ms. Using linear interpolation, what is the angle at 26 ms?
   A) 2.4°
   B) 2.6°
   C) 2.5°
   D) 3.0°

**Go further:**

- Clock drift — Wikipedia: https://en.wikipedia.org/wiki/Clock_drift — Why clocks drift and how drift is measured.
- Network Time Protocol — Wikipedia: https://en.wikipedia.org/wiki/Network_Time_Protocol — The full version of the round-trip offset calculation used in this lesson.
- Precision Time Protocol — Wikipedia: https://en.wikipedia.org/wiki/Precision_Time_Protocol — How networks synchronise clocks to well under a millisecond with hardware support.
