---
title: Commands over serial
heading: Parsing text commands, and framing binary messages
eyebrow: C12 · Lesson 33 · Commands over serial
xp: 40
---

::: hook
A UART moves bytes; a **protocol** gives them meaning. The simplest is a line of text: a person (or a script) types `pwm 30`, the board splits it into words, looks up the command, acts, and answers `ok`. Text is easy to debug with any terminal, so most development boards and many products have such a command line. Machines talking to machines often prefer **binary frames** instead: a start byte, a length, the data and a checksum, compact and quick to check, at the cost of being unreadable without a tool.
:::

::: play
- The board runs a small command line. The terminal types four commands; the board echoes each one and answers on the next line.
- Read `handle`: split the line into words, take the first as the command and the rest as arguments, check the count, convert numbers, and report errors instead of crashing.
- The terminal also sends `blink`, which isn't a command yet: the board answers with an error. Add a `blink` command that toggles the LED, and run it again.
:::
:::

```sim board
lang: micropython
attach: led P0 | green
attach: terminal | send "on\n" at 0.01 s | send "add 2 40\n" at 0.02 s | send "blink\n" at 0.03 s | send "off\n" at 0.04 s
scope: P0
run: 0.06 s
code:
from machine import UART, Pin
import time

u = UART(0, 115200)
led = Pin(0, Pin.OUT)

def handle(line):
    words = line.split()
    if not words:
        return 'error: empty line'
    cmd, args = words[0], words[1:]
    if cmd == 'on' and not args:
        led.on()
        return 'ok'
    if cmd == 'off' and not args:
        led.off()
        return 'ok'
    if cmd == 'add' and len(args) == 2:
        try:
            return str(int(args[0]) + int(args[1]))
        except ValueError:
            return 'error: add takes two numbers'
    return 'error: unknown command ' + cmd

u.write('ready\n')
while True:
    line = u.readline()
    if line:
        text = line.decode().strip()
        u.write('> ' + text + '\n' + handle(text) + '\n')
    time.sleep_ms(1)
```

::: predict
## A binary frame carries 2 start bytes, 1 length byte, a payload and 1 checksum byte. For a 4-byte payload, what fraction of the bytes is payload?

- [ ] 100%
- [ ] 80%
- [x] 50%
- [ ] 25%

::: reveal
50%: 4 payload bytes out of 8 in the frame. Framing overhead is fixed per frame, so it matters for short messages and fades for long ones: a 100-byte payload in the same frame is 96% payload.
:::
:::

::: nameit
## Text commands

A line-based protocol reads characters until a newline, then:

1. splits the line into words;
2. looks up the first word in a table of commands;
3. checks the number of arguments and converts them, rejecting anything malformed;
4. acts, and always answers, `ok`, a value or an error message, so the sender knows the command arrived.

Answering every line is what makes the protocol usable from a script: the script waits for the answer before sending the next command.

## Binary frames

| Field | Purpose |
|---|---|
| start byte(s) | find the beginning of a frame in a stream, e.g. 0xAA 0x55 |
| length | how many payload bytes follow |
| payload | the data |
| checksum | detect corrupted frames |

A receiver discards bytes until it sees the start, reads the length, collects the payload, then checks the checksum; on a mismatch it throws the frame away and searches for the next start. That receiver is a state machine (lesson 36).

## Checksums

- **Sum:** add the bytes modulo 256. Often the sender appends $(-\text{sum}) \bmod 256$, so that all bytes including the checksum add to 0.
- **XOR:** combine the bytes with exclusive-or.
- **CRC** (C7): catches far more error patterns, at the cost of more computation or a table.

A sum misses two bytes swapped; XOR misses a bit flipped in the same position in two bytes; a CRC catches both.
:::

::: example
## A payload is 0x10, 0x20, 0xF0. What's its sum checksum, and what byte makes the total zero?

::: solution
1. **Add the bytes.**
   $$\text{0x10} + \text{0x20} + \text{0xF0} = \text{0x120}$$
2. **Keep the low byte.** Modulo 256 that's 0x20, the checksum.
3. **Find the byte that makes zero.**
   $$(256 - \text{0x20}) \bmod 256 = \text{0xE0}$$

**Answer:** the checksum is 0x20, and 0xE0 makes the total zero.
:::
:::

::: example
## A command line answers each command with `ok\n` at 115,200 baud. How long does the answer take on the wire?

::: solution
1. **Count the bits.** 3 characters of 10 bits each make 30 bits.
2. **Time on the wire.**
   $$\frac{30}{115\,200}\ \text{s} = 0.26\ \text{ms}$$
3. **With an echo.** Echoing the command too roughly triples that, still fast enough for a person, but worth counting when a script sends thousands of commands.

**Answer:** 0.26 ms.
:::
:::

::: example
## Why can't a simple sum checksum detect two payload bytes swapped in order?

::: solution
1. **Addition ignores order.** 0x10 + 0x20 and 0x20 + 0x10 give the same sum, so a swap leaves the checksum unchanged.
2. **What catches a swap.** A CRC, or a Fletcher checksum that also sums the running sums, weights each byte by its position, so a swap changes the result.

**Answer:** a sum comes out the same in any order, so swapped bytes go unnoticed; a CRC or a Fletcher checksum weights each byte by its position and catches the swap.
:::
:::

::: check
given: a = 160 | 200 | 250; b = 100 | 120; c = 60 | 180
base: 16
answer: (a + b + c) - 256*floor((a + b + c)/256)

## What's the 8-bit sum checksum (modulo 256) of the bytes {a}, {b} and {c}, in hex?

::: right
Right. {answer:hex2}.
:::

::: misses
- [a + b + c] Keep only the low 8 bits: modulo 256.
- [any] Not yet. Add, then take the result modulo 256.
:::
:::

::: check
given: s = 0x20 | 0x7F | 0xC4
base: 16
answer: 256 - s

## A frame's bytes sum to {s:hex2} (mod 256). What checksum byte makes the total 0?

::: right
Right. {answer:hex2}.
:::

::: misses
- [s] That's the sum itself; the checksum is its negative modulo 256.
- [any] Not yet. $(256 - s) \bmod 256$.
:::
:::

::: check
given: p = 2 | 8 | 32 | 120; h = 3 | 4
answer: 100*p/(p + h + 1)
unit: %
tolerance: 0.5%

## A frame has {h} header bytes, a {p}-byte payload and a 1-byte checksum. What fraction of it is payload?

::: right
Right. {answer}%.
:::

::: misses
- [100*p/(p + h)] Count the checksum byte too.
- [any] Not yet. Payload over the whole frame.
:::
:::

::: check
given: n = 3 | 20 | 64; b = 9600 | 115200
answer: n*10/b*1000
unit: ms
tolerance: 0.5%

## A reply of {n} characters goes out at {b} baud. How long does it take?

::: right
Right. {answer} ms.
:::

::: misses
- [any] Not yet. 10 bits per character.
:::
:::

::: check
given: d1 = 1 | 4 | 9; d2 = 0 | 2 | 7; d3 = 5 | 8
answer: 100*d1 + 10*d2 + d3

## A command's argument arrives as the characters '{d1}', '{d2}', '{d3}' (ASCII codes 48 + digit). Accumulating `n = n*10 + (c - '0')` for each, what's n?

::: right
Right. {answer}.
:::

::: misses
- [d1 + d2 + d3] Each new digit shifts the earlier ones up a decimal place: multiply by 10.
- [any] Not yet. Multiply by 10 and add each digit.
:::
:::

::: check
kind: choice

## A receiver expects frames starting 0xAA 0x55, but it was switched on halfway through a frame. What should it do?

- [ ] Treat the next byte as a start byte
- [x] Discard bytes until it sees 0xAA followed by 0x55, then read a frame
- [ ] Reset the UART
- [ ] Ask the sender to slow down

::: misses
- [1] The next byte is probably payload; reading from it gives garbage frames.
- [3] The bytes would still arrive mid-frame.
- [4] Speed isn't the problem; finding the frame's start is.
:::
:::

::: check
kind: micropython
attach: terminal | send "mul 6 7\n" at 0.002 s | send "mul 12 x\n" at 0.004 s
run: 0.03
expect: terminal = "42\nerror\n"

## Answer `mul a b` with the product of the two whole numbers, and with `error` if they aren't numbers. Each answer is one line.

```micropython starter
from machine import UART
import time

u = UART(0, 115200)
while True:
    line = u.readline()
    if line:
        u.write('ok\n')
    time.sleep_ms(1)
```

```micropython solution
from machine import UART
import time

u = UART(0, 115200)
while True:
    line = u.readline()
    if line:
        words = line.decode().split()
        try:
            u.write(str(int(words[1]) * int(words[2])) + '\n')
        except (ValueError, IndexError):
            u.write('error\n')
    time.sleep_ms(1)
```

::: right
Right. Converting inside `try` turns bad input into an answer instead of a crash.
:::
:::

::: check
kind: c
given: A = 16 | 170 | 250; B = 32 | 85 | 200; C = 240 | 1 | 99
run: 0.01
expect: print = A + B + C - 256*floor((A + B + C)/256), 256 - (A + B + C - 256*floor((A + B + C)/256)) - 256*floor((256 - (A + B + C - 256*floor((A + B + C)/256)))/256)

## A payload is the bytes `A`, `B` and `C` ({A}, {B}, {C}). Print its 8-bit sum checksum, then the byte that would make the frame's total zero (0 if the sum is already 0).

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

int main(void) {
    print(A + B + C);
    return 0;
}
```

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

int main(void) {
    uint8_t payload[3] = {A, B, C};
    uint8_t sum = 0;
    for (int i = 0; i < 3; i++) sum += payload[i];
    print(sum);
    print((uint8_t)(-sum));
    return 0;
}
```

::: right
Right. A `uint8_t` wraps at 256 by itself, so the sum needs no explicit modulo.
:::
:::

::: check
kind: parts
given: a = 16 | 200; b = 32 | 100; c = 240 | 7

## A payload is {a}, {b}, {c}.

::: part
answer: a + b + c - 256*floor((a + b + c)/256)
tolerance: 0

### What is its 8-bit sum?

::: misses
- [any] The sum modulo 256.
:::
:::

::: part
answer: 256 - (a + b + c - 256*floor((a + b + c)/256)) - 256*step(-(a + b + c - 256*floor((a + b + c)/256)) + 0.5)
tolerance: 0

### What checksum byte makes the total 0 modulo 256?

::: misses
- [any] 256 minus the sum (0 if the sum is 0).
:::
:::
:::

::: check
kind: parts
given: n = 3 | 12 | 40; b = 9600 | 115200

## A command line answers with {n} characters at {b} baud.

::: part
answer: n*10/b*1000
unit: ms
tolerance: 0.5%

### How long is the answer on the wire?

::: misses
- [any] 10 bit-times per character.
:::
:::

::: part
answer: b/(10*n)
tolerance: 0.5%

### At most how many such answers a second?

::: misses
- [any] The reciprocal of the time.
:::
:::
:::

::: explain
## Why should a text command protocol answer every command, even with just `ok`?

::: model
Without an answer, the sender can't tell whether a command arrived, was understood or failed, or whether the board is even running. With one, a person sees the result immediately and a script can wait for each answer before sending the next command, which keeps a fast sender from overrunning a slow board, and can stop as soon as it sees an error. Making error answers specific ("add takes two numbers") turns the protocol into its own documentation for whoever uses it next.
:::
:::

::: practice

::: check
given: a = 77 | 250; b = 200 | 9; c = 31 | 128
base: 16
answer: (a + b + c) - 256*floor((a + b + c)/256)

## Sum checksum of {a}, {b}, {c}, in hex?

::: misses
- [any] Modulo 256.
:::
:::

::: check
given: s = 0x01 | 0x10 | 0x3C | 0x7F | 0xA0 | 0xC8 | 0xFF
base: 16
answer: 256 - s

## Byte that zeroes a sum of {s:hex2}?

::: misses
- [any] $256 - s$.
:::
:::

::: check
given: p = 4 | 10 | 16 | 32 | 64 | 200 | 255; h = 2 | 3 | 4
answer: 100*p/(p + h + 1)
unit: %
tolerance: 0.5%

## Payload share with {h} header bytes, {p} payload, 1 checksum?

::: misses
- [any] Payload over everything.
:::
:::
:::
