# Worksheet: Embedded communication

*Tactiverge Academy · Embedded Systems, module 5 · https://tactiverge.win/academy/embedded-systems/#embedded-communication*

Name: ______________________    Date: ____________

## Learning objectives

Tick each one when you can do it without looking at your notes.

- [ ] 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.

## Lesson 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.

Read online: https://tactiverge.win/academy/embedded-systems/embedded-communication/serial-and-uart/

#### 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

### My notes

______________________________________________

______________________________________________

## Lesson 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.

Read online: https://tactiverge.win/academy/embedded-systems/embedded-communication/i2c-shared-bus/

### 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

### My notes

______________________________________________

______________________________________________

## Lesson 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.

Read online: https://tactiverge.win/academy/embedded-systems/embedded-communication/spi-fast-transfer/

#### 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

### My notes

______________________________________________

______________________________________________

## Lesson 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.

Read online: https://tactiverge.win/academy/embedded-systems/embedded-communication/designing-message-protocols/

#### 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

### My notes

______________________________________________

______________________________________________

## Lesson 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.

Read online: https://tactiverge.win/academy/embedded-systems/embedded-communication/wireless-options/

#### 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

### My notes

______________________________________________

______________________________________________

## Lesson 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.

Read online: https://tactiverge.win/academy/embedded-systems/embedded-communication/timestamps-and-synchronisation/

#### 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°

### My notes

______________________________________________

______________________________________________

---

## Answer key (for self-checking after you try)

**Lesson 1: Serial communication and UART**

1. C — One start bit, eight data bits and one stop bit make 10. Adding a parity bit would make 11.
2. A — Each byte costs 10 bit times, so 57600 / 10 = 5760 bytes per second.
3. B — A transmitter's output must reach the other device's input. TX to TX connects two outputs together and RX to RX connects two inputs, so no data flows.
4. D — Even parity makes the total count of 1s even. 0x07 has three 1s, so the parity bit must be 1 to make four.
5. A — If the receiver samples at the wrong speed, it reads bits at the wrong moments and assembles wrong bytes. Check that both ends use the same baud rate and framing.

**Lesson 2: I2C: many devices on two wires**

1. D — Shift left by one and set the read bit: (0x3C << 1) | 1 = 0x78 | 1 = 0x79. Writing would use 0x78.
2. A — I2C uses open-drain outputs. Without pull-ups the lines would never go high, and the bus would not work at all.
3. B — A target acknowledges its address by pulling SDA low. If nobody does, the line stays high, which is a NACK.
4. C — 0xFF9C as an unsigned number is 65436. As signed two's complement it is 65436 − 65536 = −100, so −1.00 °C.
5. A — A repeated START switches from writing to reading without releasing the bus, so nothing else can start a transfer in between.

**Lesson 3: SPI: fast transfers with chip select**

1. C — Each device has its own CS line. Only the device whose CS is low takes part; the rest ignore the bus.
2. A — SPI is a shift-register exchange driven by the controller's clock. Sending a dummy byte provides the eight clock pulses that bring the device's byte in.
3. D — SCLK, MOSI and MISO are shared (3), plus one CS per device (5), so 8 in total.
4. B — If the controller samples on the wrong clock edge, every bit is read half a cycle early or late. Set CPOL and CPHA to match the datasheet.
5. C — SPI's high clock rates and lack of per-byte overhead suit bulk transfers like display data. I2C suits many slower devices on few pins; neither is designed for long distances.

**Lesson 4: Designing a message protocol**

1. A — With a length field, the receiver can find the end of every frame without a special terminator, and can reject absurd lengths.
2. B — Little-endian sends the least significant byte first: 0x34, then 0x12.
3. C — 1 + 2 + 3 equals 2 + 1 + 3. A CRC depends on the position of every bit, so it catches reorderings like this that a sum cannot.
4. D — The 0xAA may have been an ordinary data byte, so the real frame boundary could be just after it. Stepping one byte forward lets the parser resynchronise safely.
5. B — Protocols change as projects grow. A version field lets a receiver tell formats apart instead of misreading a new frame as an old one.

**Lesson 5: Wireless options and trade-offs**

1. C — Power falls as 1 / distance². Tripling the distance gives 1 / 3² = 1/9 of the power.
2. A — 30 mA × (5 / 1000) = 0.15 mA. Short, infrequent transmissions keep the average tiny.
3. B — Long-range sub-GHz radios trade very low data rates for long range and low power, which suits small, infrequent messages over kilometres. SPI is not a wireless link at all.
4. D — A heartbeat with a timeout lets the robot notice silence and make itself safe without needing any message to arrive.
5. B — Control decisions depend on the current state. Timestamps or sequence numbers let the robot discard commands that are too old to be valid.

**Lesson 6: Timestamps and synchronising devices**

1. B — 10 ppm × 86,400 s = 0.864 s per day.
2. C — Latency from conversion, transfer and processing means the arrival time is late. Fusing on arrival time builds that delay into the result.
3. D — offset = ((105 − 0) + (106 − 11)) / 2 = (105 + 95) / 2 = 100 ms. The round-trip delay is 11 − 1 = 10 ms.
4. A — The method splits the measured travel time equally between the two directions. If one direction is slower, the estimate is off by half the difference.
5. B — 26 ms is 60 % of the way from 20 to 30 ms, so 2.0 + 0.6 × 1.0 = 2.6°.

---

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.
