Section 6.24

USB CDC ACM

Full name: Universal Serial Bus Communications Device Class, Abstract Control Model.

Definition

USB CDC ACM is the standard way for a USB device to appear to a computer as a serial port. CDC, the Communications Device Class, is a USB class specification for communication devices; ACM, the Abstract Control Model, is its part for modem-like devices controlled by commands. Common operating systems include a generic driver for it, so the device appears as a serial port, such as /dev/ttyACM0 on Linux, without a vendor driver. Programs then exchange a stream of bytes with the device, with no message boundaries.

The idea

A microcontroller §6.1 with a USB port needs a command channel to a computer. A custom USB protocol would need a custom driver on every computer, and a UART §6.23 (universal asynchronous receiver-transmitter), the simple serial interface, would need a separate USB-to-serial adapter. With CDC ACM, the firmware presents itself as a serial port: every terminal program and serial library, such as pyserial §12.36 in Python §12.23, can open it, and the operating system’s built-in driver does the USB work.

What crosses the link is a byte stream: the bytes arrive complete and in order, but grouped arbitrarily. A 100-byte command written by the host may reach the device as 64 bytes and then 36, and two short commands written quickly may arrive in one read. A conveyor belt carrying letters is a fair picture: it keeps their order but does not mark where one word ends, so the application must mark the words itself, with a length in front of each or a separator that cannot appear inside a word. The picture stops being accurate in one respect: USB does move the bytes in packets, but buffer sizes and timing set the packet boundaries, not the application’s messages.

How it works

What the device declares. When the device is plugged in, the host reads its descriptors, the data structures in which a USB device describes itself. An endpoint is a numbered buffer in the device that forms one end of a USB data channel, and an interface is a group of endpoints that serve one purpose. A CDC ACM function declares two interfaces:

Control requests. The host configures the function with class-specific requests. SET_LINE_CODING and GET_LINE_CODING carry the line coding: the baud rate, stop bits, parity and data bits, 7 bytes in all. SET_CONTROL_LINE_STATE carries two bits, DTR (data terminal ready) and RTS (request to send), named after control lines of a serial cable. For a device that consumes the data itself, the line coding is only a stored value and does not change the speed of the USB link; only a USB-to-UART bridge passes it on to a real UART. Host serial drivers usually set DTR when a program opens the port, so firmware often treats DTR as the sign that a reader is present.

Moving the bytes. The data travels in packets. On full-speed USB, which signals at 12 megabits per second, a bulk packet carries at most 64 bytes; on high-speed USB, at 480 megabits per second, at most 512. A packet shorter than the maximum ends a transfer, and a zero-length packet ends a transfer whose length is an exact multiple of the maximum. Every packet carries a CRC §4.32 (cyclic redundancy check), an error-detecting code, and a packet with an error is sent again, so the bytes on the bus arrive in order and uncorrupted. The host drives all traffic: the device can send only when the host asks for data. If no host program reads, the host may stop asking, the device’s transmit buffer fills, and the firmware’s writes wait or fail, depending on its driver.

The host’s terminal layer. On Linux and other POSIX (Portable Operating System Interface) systems, the port is a terminal device whose default settings serve a person typing text. Unless the program switches the port to raw mode, the terminal layer may echo received bytes back to the device, convert carriage-return bytes into line-feed bytes, hold input until a line-feed byte arrives, and treat the bytes 0x11 and 0x13 as commands to resume and pause output. Each of these corrupts binary data. Serial libraries such as pyserial set raw mode when they open a port.

The firmware side. The device’s USB stack handles enumeration, the start-up exchange in which the host reads the descriptors and configures the device, and the class requests, and gives the firmware a byte-stream interface. In the legacy USB device stack of the Zephyr RTOS §6.33 (real-time operating system), a CDC ACM function appears to firmware as a UART device, so firmware uses the calls it would use for a UART. Received bytes arrive through a callback §14.22, a function the stack calls when data is ready, in whatever chunks the packets and buffers produce.

The application’s framing. Above this byte stream the application defines its own messages, called frames, with these parts:

  1. A boundary rule. Length-prefix framing §4.30 puts a fixed-size field at the start of each frame that states how many bytes follow. Alternatively, a delimiter, a reserved byte value, ends each frame, and payload bytes equal to it must be escaped or encoded away. COBS (consistent overhead byte stuffing) is a standard encoding that removes every zero byte from a payload, so that zero can serve as the delimiter.

  2. A maximum frame size, checked before any memory is reserved for the frame.

  3. An error check, usually a CRC over the whole frame. USB has already checked the bus, so this check catches what USB cannot: bytes lost to a full buffer, stale bytes from an earlier session, and a parser that has fallen out of step with the frames.

  4. A resynchronization rule for finding the next frame after a bad one. With a delimiter, the receiver discards bytes up to the next delimiter; with a length prefix, it needs a fixed start marker and the error check to recognize a frame start again.

  5. A type and version field, so that the receiver knows how to read the rest.

  6. A request identifier or sequence number, so that each response can be matched to its request and lost or repeated messages are noticed, also across a reconnection.

  7. Timeouts §9.34 and resets: a partial frame that stops arriving is discarded after a time limit, and the parser is reset when the port is opened or the device restarts, so that the tail of an old frame is never joined to a new one.

Authentication §1.6 of the sender, when needed, is a further layer; none of these parts provides it.

Worked example

Chunked reads. The application’s frame is one length byte LL, at most 64, followed by LL payload bytes. The host sends two frames, written here in hexadecimal: 03 0A 14 1E (length 3, payload 0A 14 1E, the values 10, 20 and 30) and 02 05 06 (length 2, payload 05 06), seven bytes in all. The firmware’s callback receives them in three chunks: 03 0A, then 14 1E 02, then 05 06.

The parser keeps its state between chunks:

  1. After chunk 1 it has read L=3L = 3 and 1 payload byte. It needs 3−1=23 - 1 = 2 more, so it delivers nothing yet.

  2. Chunk 2 supplies 14 1E, which completes the first frame: the parser delivers the payload 0A 14 1E. The remaining byte 02 is the next length, L=2L = 2, with no payload bytes so far.

  3. Chunk 3 supplies 05 06 and completes the second frame: the parser delivers the payload 05 06.

A parser that treated each chunk as one message would have produced three wrong messages: 03 0A, 14 1E 02 and 05 06. The correct parser delivers the same two frames however the seven bytes are split, including all seven in a single chunk.

A payload encoded with COBS. In a COBS-encoded frame, each code byte cc is followed by c−1c - 1 data bytes; after copying them, the decoder outputs a zero byte, unless the frame has ended. (The code 0xFF is the exception: it stands for 254 data bytes with no zero after them.) The payload 11 00 22 splits at its zero into the groups 11 and 22; each group gets a code byte equal to its length plus 1, and the frame on the wire is 02 11 02 22 00, where the final 00 is the delimiter. Decoding: code 02, copy 11, output a zero; code 02, copy 22; the frame ends, so no zero follows, and the result is 11 00 22. The encoded bytes contain no zero, so a receiver that has lost track discards bytes up to the next 00 and starts again. For a payload shorter than 254 bytes, COBS adds exactly 1 byte, plus the delimiter.

Stated precisely

While the device stays connected and configured, the CDC ACM data channel gives this contract: the bytes that one side writes and the other side reads arrive in the order written, unchanged by the bus and without duplicates. The contract says nothing about how the bytes are grouped into reads. It does not cover bytes discarded because a buffer in the firmware or on the host was full, bytes changed by a host terminal layer left outside raw mode, or bytes lost when a side disconnects, closes the port or restarts.

A framing parser meets its own contract when three conditions hold.

  1. Chunking invariance: for every way of splitting the same byte sequence into reads, it delivers the same sequence of frames.

  2. Bounds: it never reads a byte it has not received, and it rejects any frame whose declared or accumulated length exceeds the maximum before storing it.

  3. Recovery: after any invalid byte sequence, it resumes correct operation at the next frame start that its resynchronization rule can recognize.

Limits and common mistakes

The baud rate setting does not set the speed of a CDC ACM device that consumes the data itself. Real throughput depends on the packet size, how often the host asks for data, and how fast both sides empty their buffers.

A USB packet is not an application message. Packet size, read size and write size are all unrelated to frame boundaries.

Opening and closing the port matters. Bytes the device sends while no program has the port open can wait in buffers and reach the next program that opens it, so a new session should discard old input before its first request. A device restart makes the port disappear and reappear, sometimes under a different name, and the host program must open it again.

USB error checking is not authentication. It catches accidental errors on the bus; it does not stop anyone with access to the computer from sending chosen bytes to the device.

A line-feed delimiter works only for text. A binary payload that contains the byte 0x0A breaks it, unless the payload is escaped or encoded.

Questions answered

What framing does the application add above a byte stream?

Above a byte stream such as a USB CDC ACM serial port, the application adds a frame format that marks where each message begins and ends, because the stream keeps only the order of the bytes, not their grouping. The core is a boundary rule: a length field at the start of each frame, or a delimiter byte at its end with every copy of the delimiter inside the payload escaped or encoded, for example with COBS (consistent overhead byte stuffing). Around it come a maximum frame size checked before buffering; an error check such as a CRC (cyclic redundancy check) over the frame, to detect lost, stale or misaligned bytes; a rule for resynchronizing after a bad frame; a type and version field; a request identifier or sequence number to match responses and detect lost or repeated messages; and a timeout for incomplete frames, with a parser reset when the port is opened or the device restarts.

The parser must deliver the same frames however the bytes are split into reads: neither the USB packet size nor the size of one write or read call marks a message boundary. If the sender must be authenticated, a message authentication code §5.7 over the frame is a further layer on top.

Related entries: Length-prefix framing (§4.30), Deserialization (§4.29), Asynchronous completion (§9.28), UART (§6.23), Checksum versus CRC (§4.32). Further reading: [178].