---
title: "Embedded lab: talking to the outside"
heading: CRCs, framing, ring buffers and bus timing, in Python and C
eyebrow: C12 · Lesson 35 · Embedded lab
xp: 50
---

::: hook
A device that talks over a serial link needs a way to find where each message starts, a check that it arrived intact, a buffer that never loses a byte while the program is busy, and a budget for how long each bus transaction takes. Both ends of the link need the same code: the firmware, and a program on a computer that talks to it. This lab writes the computer's side in Python (a CRC-16, COBS framing, a ring buffer and a bus-timing calculator), then the board's side of a CRC in C, and checks that both agree on the standard test message.
:::

::: play
- COBS framing removes every zero byte from a message, so a zero can mark the end of each frame. The curve is the worst-case overhead: one extra byte per 254, plus one, against the message length.
- For short messages the overhead is a single byte, under 1% once a message passes 100 bytes; for long messages it approaches 1/254, about 0.4%.
- Compare with escaping schemes such as SLIP, whose overhead can double a message full of the special byte.
:::

```sim plot
view: graph
x: n = 1..1000 bytes
y: o = 0..10 %
samples: 1000
plot: (floor(n/254) + 1)/n*100 | label: COBS worst-case overhead
plot: 100/254 + 0*n | dashed | label: long-message limit
```

::: predict
## A 300-byte message containing no zeros is COBS-encoded. How long is the result, not counting the delimiter?

- [ ] 300 bytes
- [ ] 301 bytes
- [x] 302 bytes
- [ ] 600 bytes

::: reveal
COBS splits zero-free data into blocks of at most 254 bytes, each with a leading length byte: 254 + 1 and 46 + 1, so 302 bytes. A message with zeros in it costs no more, since each zero is replaced by a length byte.
:::
:::

::: nameit
## The pieces

- **CRC-16/CCITT-FALSE:** polynomial 0x1021, starting value 0xFFFF, bits processed from the top. Its check value, the CRC of the ASCII text "123456789", is 0x29B1; every implementation should be tested against it.
- **CRC-8:** polynomial 0x07, starting value 0; its check value is 0xF4.
- **COBS** (consistent overhead byte stuffing): each block of up to 254 nonzero bytes is sent as its length plus one, followed by the block; the zero that ended the block is implied. The encoded frame has no zeros, so 0x00 delimits frames.
- **Ring buffer:** a power-of-two array with head and tail counters; full when head − tail equals the size; a full buffer drops the byte and counts an overrun.
- **I²C timing:** each byte is 9 clocks with its acknowledge; a register read is address, register, repeated start, address and the data bytes, plus about 3 clocks for the start, repeated start and stop.
:::

::: check
kind: python

## Write `crc16(data)`: CRC-16/CCITT-FALSE of a `bytes` object (polynomial 0x1021, start 0xFFFF, most significant bit first, no final XOR).

```python starter
def crc16(data):
    return sum(data) & 0xFFFF
```

```python solution
def crc16(data):
    crc = 0xFFFF
    for b in data:
        crc ^= b << 8
        for _ in range(8):
            if crc & 0x8000:
                crc = ((crc << 1) ^ 0x1021) & 0xFFFF
            else:
                crc = (crc << 1) & 0xFFFF
    return crc
```

```python tests
assert crc16(b"123456789") == 0x29B1, "The standard check value is 0x29B1."
assert crc16(b"") == 0xFFFF, "Nothing processed: the starting value."
assert crc16(b"12") != crc16(b"21"), "Unlike a sum, a CRC sees the order."
assert crc16(b"A") == 0xB915, "One byte, 'A': 0xB915."
```

::: right
Right. Matching the published check value is the test that matters: CRC variants differ in polynomial, starting value, bit order and final XOR, and every combination is in use somewhere.
:::
:::

::: check
kind: python

## Write `cobs_encode(data)` and `cobs_decode(enc)` on lists of byte values. Encoding produces no zeros; decoding reverses it exactly.

```python starter
def cobs_encode(data):
    return list(data)

def cobs_decode(enc):
    return list(enc)
```

```python solution
def cobs_encode(data):
    out, block = [], []
    for b in data:
        if b == 0:
            out += [len(block) + 1] + block
            block = []
        else:
            block.append(b)
            if len(block) == 254:
                out += [255] + block
                block = []
    out += [len(block) + 1] + block
    return out

def cobs_decode(enc):
    out, i = [], 0
    while i < len(enc):
        code = enc[i]
        i += 1
        out += enc[i:i + code - 1]
        i += code - 1
        if code < 255 and i < len(enc):
            out.append(0)
    return out
```

```python tests
assert cobs_encode([0x11, 0x22, 0x00, 0x33]) == [3, 0x11, 0x22, 2, 0x33], "The zero becomes a length byte."
assert cobs_encode([0]) == [1, 1], "A lone zero: two empty blocks."
assert len(cobs_encode([5] * 300)) == 302, "300 zero-free bytes: 302 encoded."
for d in ([1, 2, 3], [0, 0], [5] * 300, [0, 0, 0, 7], [7] * 254):
    e = cobs_encode(d)
    assert 0 not in e, "No zeros in the encoding."
    assert cobs_decode(e) == d, f"Round trip failed for {d[:6]}..."
```

::: right
Right. A receiver can now resynchronize after any error by waiting for the next zero.
:::
:::

::: check
kind: python

## Write a class `Ring(size)` (size a power of two) with `put(b)` (returns False and counts an overrun when full), `get()` (returns None when empty), `count()` and an `overruns` attribute. Use free-running head and tail counters masked with `size - 1`.

```python starter
class Ring:
    def __init__(self, size):
        self.data = []
        self.overruns = 0
    def put(self, b):
        self.data.append(b)
        return True
    def get(self):
        return self.data.pop(0) if self.data else None
    def count(self):
        return len(self.data)
```

```python solution
class Ring:
    def __init__(self, size):
        self.size = size
        self.buf = [0] * size
        self.head = 0
        self.tail = 0
        self.overruns = 0
    def put(self, b):
        if self.head - self.tail == self.size:
            self.overruns += 1
            return False
        self.buf[self.head & (self.size - 1)] = b
        self.head += 1
        return True
    def get(self):
        if self.head == self.tail:
            return None
        b = self.buf[self.tail & (self.size - 1)]
        self.tail += 1
        return b
    def count(self):
        return self.head - self.tail
```

```python tests
r = Ring(4)
assert all(r.put(i) for i in range(4)), "Four bytes fit in four slots with free-running counters."
assert r.put(99) is False and r.overruns == 1, "The fifth is dropped and counted."
assert [r.get() for _ in range(5)] == [0, 1, 2, 3, None], "Out in order, then empty."
for i in range(10):
    r.put(i)
    assert r.get() == i, "Wrapping around many times."
assert r.count() == 0, "Empty again."
```

::: right
Right. Free-running counters let all of the slots be used, where comparing masked indices must keep one empty to tell full from empty.
:::
:::

::: check
kind: python

## Write `i2c_read_time(n, f)`: seconds for an I²C register read of `n` data bytes at clock `f`: 9 clocks for each of the address, register, repeated address and n data bytes, plus 3 for the start, repeated start and stop. Then `max_reads(n, f, budget)`: how many whole such reads fit in `budget` seconds.

```python starter
def i2c_read_time(n, f):
    return n * 8 / f

def max_reads(n, f, budget):
    return 0
```

```python solution
def i2c_read_time(n, f):
    return (9 * (3 + n) + 3) / f

def max_reads(n, f, budget):
    return int(budget // i2c_read_time(n, f))
```

```python tests
assert abs(i2c_read_time(2, 100e3) - 480e-6) < 1e-12, "Two bytes at 100 kHz: 48 clocks, 480 µs."
assert abs(i2c_read_time(6, 400e3) - 210e-6) < 1e-12, "Six bytes at 400 kHz: 84 clocks, 210 µs."
assert max_reads(2, 100e3, 0.01) == 20, "Twenty two-byte reads in 10 ms at 100 kHz."
assert max_reads(2, 400e3, 0.01) == 83, "Eighty-three at 400 kHz."
```

::: right
Right. A sensor polled at 1 kHz over a 100 kHz bus would take half the bus by itself.
:::
:::

::: check
kind: c
run: 0.01
expect: print = 244

## Compute the CRC-8 (polynomial 0x07, starting value 0, most significant bit first) of the nine bytes of "123456789" on the board, and print it. The check value is 0xF4, 244.

```c starter
#include "board.h"

const char msg[] = "123456789";

int main(void) {
    uint8_t crc = 0;
    for (int i = 0; i < 9; i++)
        crc += msg[i];
    print(crc);
    return 0;
}
```

```c solution
#include "board.h"

const char msg[] = "123456789";

int main(void) {
    uint8_t crc = 0;
    for (int i = 0; i < 9; i++) {
        crc ^= msg[i];
        for (int b = 0; b < 8; b++)
            crc = (crc & 0x80) ? (uint8_t)((crc << 1) ^ 0x07) : (uint8_t)(crc << 1);
    }
    print(crc);
    return 0;
}
```

::: right
Right. The same check value on the board and in any reference implementation means both ends of a link will agree.
:::
:::

::: explain
## Why does a framing scheme like COBS make a serial link recover from errors better than sending a length byte at the start of each message?

::: model
With a length byte, the receiver finds the next message by counting bytes from the start of this one. If a byte is lost or a length is corrupted, it counts to the wrong place and every message after that is misread, with no way to tell where the real boundaries are. COBS removes every zero from the data and uses zero only as the end-of-frame marker, so the receiver can always resynchronize: whatever went wrong, it discards bytes until the next zero, and the frame after it is read correctly. Combined with a CRC on each frame, a damaged frame is detected and dropped while the rest of the stream carries on.
:::
:::
