Skip to content
systemcoding.dev
Embedded

The Complete Guide to USB Device Firmware on Microcontrollers

A practical guide to USB device firmware: enumeration, descriptors, endpoints, device classes, stacks, hardware, a first STM32 device, debugging and updates.

25 min read
Summarize in AI
Flat illustration of a microcontroller wired to an LED and a sensor, with the Arm, C and STMicroelectronics logos.

A microcontroller with a USB port can be a serial console, a keyboard, a disk, a MIDI instrument, a firmware updater or a custom instrument, and the hardware that makes it possible costs nothing beyond a connector. The software is where the effort goes, and it is unlike most embedded work because the other side is in charge. A UART peripheral sends bytes when your program tells it to. A USB device sends nothing until a host that you cannot see, running an operating system you do not control, asks for it, in a protocol with its own vocabulary of descriptors, endpoints, classes and requests. Programs that ignore that structure work on one laptop and fail on another, enumerate and do nothing, or show up as "Unknown Device" with no explanation. This guide covers the structure first and the code second, for a microcontroller acting as a USB device. It uses the USB 2.0 specification (chapter 9, "USB Device Framework"), the class specifications for the common device classes, TinyUSB 0.17 for the code and the STM32F4 as the example chip. Every section ends at a point where you could build and test something, and the later posts in this series go deeper into each class and technique.

USB from the device's point of view

USB is a host-centric bus. One host, usually a computer, controls everything. Devices never start a conversation: a device answers when the host polls it, and it can only prepare data and wait to be asked. This single fact explains most of the design. "Sending data" from firmware means placing bytes in a buffer that the hardware offers to the host the next time the host polls the endpoint, and "receiving" means the hardware has already stored bytes the host sent and your code reads them out. There is no way to interrupt the host.

The bus has four speeds:

SpeedSignaling rateTypical microcontrollers
Low speed1.5 Mbit/sMice and keyboards, rarely on a microcontroller as a device
Full speed12 Mbit/sNearly every microcontroller with USB: STM32F0, F1, F4 (OTG_FS), RP2040, nRF52840, ESP32-S2 and S3, SAMD
High speed480 Mbit/sLarger parts with a high-speed PHY or ULPI interface: STM32F4 and F7 (OTG_HS), H7, i.MX RT
SuperSpeed5 Gbit/s and aboveApplication processors; not microcontrollers

Most microcontroller firmware is full speed, and the practical ceiling for bulk data on a full-speed link is about 1.2 MB/s. High speed raises it by a large factor, and needs a PHY and a more careful board.

A device is identified on the bus by an address that the host assigns, and talks to the host through endpoints, numbered pipes, each with a direction. The host sees a device as a tree of descriptors that it reads when the device is plugged in, and the rest of the protocol follows from what those descriptors say.

What happens when you plug it in

The sequence of events is the same for every device, and it is worth knowing in order because failures happen at specific steps.

  1. Attach. At full speed the device connects a 1.5 kilo-ohm pull-up resistor from D+ to 3.3 V. The host, which has 15 kilo-ohm pull-downs on both data lines, sees D+ go high and knows a full-speed device is present. Many microcontrollers have this pull-up inside the USB block, enabled by software; some, such as the STM32F1, need an external resistor. Until firmware connects the pull-up, the device is invisible, which is how a program can disconnect and reconnect itself.

  2. Reset. The host drives both lines low for at least 10 ms. The device goes to its default state, address 0.

  3. First descriptor request. The host reads the first 8 bytes of the device descriptor to learn the maximum packet size of endpoint 0.

  4. Address assignment. After another reset (hosts differ), the host sends SET_ADDRESS, and the device uses the new address from then on.

  5. Descriptor reads. The host reads the full device descriptor, the configuration descriptor with all its interfaces and endpoints, and the string descriptors for the manufacturer, product and serial number.

  6. Configuration. The host sends SET_CONFIGURATION, and the device enables its endpoints. The operating system loads a driver for each interface based on its class codes, vendor and product IDs.

All of steps 3 to 6 run on endpoint 0, the default control pipe, which every device has. A device that fails at step 3 usually has a clock or wiring problem; one that fails at step 5 has a descriptor problem; one that completes step 6 and does nothing has a class or application problem. That diagnosis alone saves hours.

Descriptors: how a device describes itself

Descriptors are small binary structures, defined in chapter 9 of the specification, that the device returns when the host asks. Four levels matter.

The device descriptor (18 bytes) carries the USB version, the device class, the size of endpoint 0's packets (8, 16, 32 or 64 bytes), the vendor ID and product ID, a device release number, indices of three strings and the number of configurations. The vendor ID is assigned by the USB Implementers Forum, and the product ID is yours. A product that ships needs a vendor ID you are entitled to use: buy one from the USB-IF, use one from your chip vendor's licensing program, or use the pid.codes registry for open-source hardware. Test IDs such as 0x1209:0x0001 are for development only.

The configuration descriptor (9 bytes) says how many interfaces the configuration has, how much current it needs in units of 2 mA, whether the device is self-powered and supports remote wakeup, and its total length, including everything that follows it. The host reads the configuration descriptor and everything below it in one transfer.

An interface descriptor (9 bytes) describes one function: its number, the class, subclass and protocol codes that tell the host which driver to bind, and the number of endpoints. A device with a serial port and a keyboard has several.

An endpoint descriptor (7 bytes) describes one data pipe: its address, with the direction in bit 7 (1 for IN, device to host), its transfer type, its maximum packet size and its polling interval.

String descriptors give human-readable text in UTF-16LE. A real device always provides a serial number string, because hosts use it to tell two identical devices apart.

Here is a complete device descriptor in C, written so that the layout is visible:

device_descriptor.cc
#include <stdint.h>

static const uint8_t device_desc[18] = {
	18,             /* bLength */
	1,              /* bDescriptorType: device */
	0x00, 0x02,     /* bcdUSB: USB 2.00 */
	0xEF,           /* bDeviceClass: miscellaneous (composite with IAD) */
	0x02,           /* bDeviceSubClass: common */
	0x01,           /* bDeviceProtocol: interface association */
	64,             /* bMaxPacketSize0 */
	0x09, 0x12,     /* idVendor: 0x1209 */
	0x01, 0x00,     /* idProduct: 0x0001 (test ID) */
	0x00, 0x01,     /* bcdDevice: 1.00 */
	1,              /* iManufacturer */
	2,              /* iProduct */
	3,              /* iSerialNumber */
	1,              /* bNumConfigurations */
};

The most common descriptor bugs are a wTotalLength in the configuration descriptor that does not add up (the host stops reading early and never sees later interfaces), endpoint directions written backwards, and a bMaxPacketSize0 that does not match what the controller supports. The post on descriptors, endpoints and enumeration goes through each field.

Endpoints and transfer types

Every non-control endpoint has one of three transfer types, chosen for its data, plus the control type that endpoint 0 uses.

TypeWhat it guaranteesTypical useFull-speed packet size
ControlDelivery, with a setup, optional data and status stageEnumeration, requests8 to 64 bytes
BulkDelivery, no timing guarantee; uses spare bandwidthSerial data, disk blocks, firmware64 bytes
InterruptDelivery with a bounded polling intervalKeyboards, mice, status, control messagesup to 64 bytes
IsochronousTiming, no retry on errorsAudio, videoup to 1,023 bytes

The names mislead: an interrupt endpoint is not a hardware interrupt, it is a pipe the host polls at a regular interval. A device that must deliver small messages with bounded latency uses interrupt endpoints. A device that moves data in bulk uses bulk endpoints, and accepts that the host decides when. Direction is always the host's view: IN endpoints carry data from the device to the host and OUT endpoints the other way. Endpoint numbers are 0 to 15, and a given number can have an IN and an OUT of its own.

A microcontroller's USB block has a fixed amount of packet memory and a fixed number of endpoints. A full-speed STM32F4 OTG_FS core has four endpoints besides the control pair, sharing a 1.25 KB FIFO RAM. The RP2040 supports 16 in each direction in a 4 KB buffer area. These limits decide how many functions your device can have, and they are the first thing to check before designing a composite device.

Device classes: not writing the protocol yourself

USB defines classes, standard protocols for common kinds of device, and the major operating systems ship drivers for them. A device that follows a class specification needs no driver installation, which is the point. The ones that cover most microcontroller projects:

ClassClass codeWhat it gives youHost support
CDC ACM0x02 and 0x0AA virtual serial portBuilt-in on Linux, macOS, Windows 10 and later
HID0x03Keyboards, mice, gamepads, custom reportsBuilt-in everywhere
Mass storage (MSC)0x08A disk the host mountsBuilt-in everywhere
Audio and MIDI0x01Sound cards, MIDI instrumentsBuilt-in everywhere
DFU0xFE, subclass 1Firmware updatesdfu-util
Vendor specific0xFFAny protocol you designlibusb, WinUSB, or your own driver

The decision rule is simple. If a standard class does what you need, use it. CDC is the default answer for "I want a console", HID for small custom inputs and outputs (a surprisingly good vehicle for custom data, since a HID device with a generic report needs no driver on any system), MSC for "the user should drag files onto it" and MIDI for music hardware. Use a vendor-specific interface when you need a custom data pipe and can supply a host program, with the Microsoft OS 2.0 descriptors so that Windows loads WinUSB with no installer.

A device can have several classes at once. That is a composite device, which needs an interface association descriptor to group the interfaces of each function and the Miscellaneous device class in the device descriptor. The post on composite devices shows the CDC plus HID case.

Choosing a stack

You can write a USB device stack yourself, and nobody should. A stack provides the protocol engine for endpoint 0, the class drivers and the driver for your chip's USB controller. The options on a microcontroller are TinyUSB, ST's USB Device Library (STM32 only), and the vendor or RTOS stacks (NXP, Nordic, Zephyr, Microchip). TinyUSB is MIT licensed, runs on many families, needs no RTOS and no allocation, and is the stack inside the Raspberry Pi Pico SDK and ESP-IDF. ST's library is integrated with CubeMX and the STM32 HAL. The choice is a project decision, covered in its own post. For portability, this guide uses TinyUSB, and the structure of the code carries over to the others: a descriptor set, a set of class callbacks and a loop that serves the stack.

Whatever you choose, keep your application behind a small interface (usb_write, usb_read, usb_connected). The stack's calls will not outlive your product; the application should.

The hardware you need to get right

USB failures that look like firmware bugs are often hardware, and a few decisions at the schematic stage prevent them. The full checklist has its own post; these are the ones that decide whether a first board enumerates.

The 48 MHz clock. A full-speed USB controller needs a 48 MHz clock with a tolerance of about 0.25 percent. The internal RC oscillator of most microcontrollers is not that good. The usual source is a crystal feeding a PLL whose USB output divides to exactly 48 MHz. On the STM32F4 the PLL's Q output provides it: with an 8 MHz crystal and PLLM = 8, PLLN = 336, PLLP = 2, the system clock is 168 MHz and PLLQ = 7 gives 48 MHz. Parts with an internal 48 MHz oscillator and clock recovery (the HSI48 with CRS on STM32F0x2, L4, G4) can run crystal-less, because the recovery trims against the host's start-of-frame packets. If the clock is wrong, the symptom is erratic enumeration or error -71 in the host log.

The data pins and the pull-up. D+ and D- connect to the chip's USB pins, directly or through 22 ohm resistors if the data sheet asks for them. On parts with an internal pull-up on D+, software enables it, and an external one on top is an error. On parts without one, such as the STM32F1, use an external 1.5 kilo-ohm resistor to 3.3 V, ideally through a transistor or GPIO so that firmware can disconnect.

Protection and power. Put an ESD protection array on D+, D- and VBUS at the connector. Keep capacitance on VBUS to 10 microfarads or less behind the connector, or add a soft start, because a host port cannot supply the inrush for more. A bus-powered device may draw 100 mA before configuration and 500 mA after, and must fall below 2.5 mA in suspend. USB-C connectors on a device need a 5.1 kilo-ohm pull-down on each CC pin, or a compliant host provides no power.

VBUS sensing. Self-powered devices sense VBUS to know whether a host is attached and should disconnect the pull-up when it is not. Bus-powered devices lose power when VBUS drops, and can disable sensing. On the STM32F4 OTG_FS core, the registers GCCFG.NOVBUSSENS and VBUSBSEN control this, and a board without the sense pin wired must set NOVBUSSENS or the device never attaches.

Check those four first when a new board does not enumerate, before any firmware debugging.

A first device: a USB serial port on an STM32

The example below is a complete CDC serial device on an STM32F407 with TinyUSB 0.17, no ST middleware. It does the whole job in about a hundred lines, which makes the structure visible. The pieces are the stack configuration, the descriptors, the interrupt hookup and the main loop.

The stack is configured in tusb_config.h:

tusb_config.hc
#ifndef TUSB_CONFIG_H
#define TUSB_CONFIG_H

#define CFG_TUSB_MCU            OPT_MCU_STM32F4
#define CFG_TUSB_OS             OPT_OS_NONE
#define CFG_TUSB_RHPORT0_MODE   (OPT_MODE_DEVICE | OPT_MODE_FULL_SPEED)

#define CFG_TUD_ENDPOINT0_SIZE  64
#define CFG_TUD_CDC             1
#define CFG_TUD_CDC_RX_BUFSIZE  512
#define CFG_TUD_CDC_TX_BUFSIZE  512
#define CFG_TUD_CDC_EP_BUFSIZE  64

#endif

The descriptors come from callbacks that the stack calls during enumeration:

usb_descriptors.cc
#include "tusb.h"

static const tusb_desc_device_t desc_device = {
	.bLength            = sizeof(tusb_desc_device_t),
	.bDescriptorType    = TUSB_DESC_DEVICE,
	.bcdUSB             = 0x0200,
	.bDeviceClass       = TUSB_CLASS_MISC,
	.bDeviceSubClass    = MISC_SUBCLASS_COMMON,
	.bDeviceProtocol    = MISC_PROTOCOL_IAD,
	.bMaxPacketSize0    = CFG_TUD_ENDPOINT0_SIZE,
	.idVendor           = 0x1209,
	.idProduct          = 0x0001,
	.bcdDevice          = 0x0100,
	.iManufacturer      = 1,
	.iProduct           = 2,
	.iSerialNumber      = 3,
	.bNumConfigurations = 1,
};

const uint8_t *tud_descriptor_device_cb(void)
{
	return (const uint8_t *)&desc_device;
}

#define CONFIG_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_CDC_DESC_LEN)

static const uint8_t desc_config[] = {
	TUD_CONFIG_DESCRIPTOR(1, 2, 0, CONFIG_TOTAL_LEN, 0x00, 100),
	TUD_CDC_DESCRIPTOR(0, 4, 0x81, 8, 0x02, 0x82, 64),
};

const uint8_t *tud_descriptor_configuration_cb(uint8_t index)
{
	(void)index;
	return desc_config;
}

static const char *const strings[] = {
	(const char[]){ 0x09, 0x04 },
	"Example Co",
	"STM32 Serial",
	"0001",
	"CDC",
};

static uint16_t str_buf[32];

const uint16_t *tud_descriptor_string_cb(uint8_t index, uint16_t langid)
{
	(void)langid;
	unsigned n;

	if (index == 0) {
		str_buf[1] = 0x0409;
		n = 1;
	} else if (index < sizeof strings / sizeof strings[0]) {
		for (n = 0; n < 31 && strings[index][n]; n++)
			str_buf[1 + n] = (uint8_t)strings[index][n];
	} else {
		return NULL;
	}
	str_buf[0] = (uint16_t)((TUSB_DESC_STRING << 8) | (2 * n + 2));
	return str_buf;
}

Three small pieces connect it to the chip: the pins and clock set up before the stack starts, the interrupt handler that feeds it, and the loop that runs it:

main.cc
#include <string.h>
#include "stm32f4xx.h"
#include "tusb.h"

extern void system_clock_168mhz(void);   /* PLLQ gives 48 MHz */
extern void usb_gpio_init(void);          /* PA11 and PA12, AF10 */

void OTG_FS_IRQHandler(void)
{
	tud_int_handler(0);
}

int main(void)
{
	system_clock_168mhz();
	usb_gpio_init();
	USB_OTG_FS->GCCFG &= ~(USB_OTG_GCCFG_VBUSBSEN | USB_OTG_GCCFG_VBUSASEN);
	USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_NOVBUSSENS;

	NVIC_SetPriority(OTG_FS_IRQn, 5);
	NVIC_EnableIRQ(OTG_FS_IRQn);
	tusb_init();

	for (;;) {
		tud_task();

		if (tud_cdc_connected() && tud_cdc_available()) {
			uint8_t buf[64];
			uint32_t n = tud_cdc_read(buf, sizeof buf);

			for (uint32_t i = 0; i < n; i++)
				if (buf[i] >= 'a' && buf[i] <= 'z')
					buf[i] -= 32;
			tud_cdc_write(buf, n);
			tud_cdc_write_flush();
		}
	}
}

Flash it and a serial port appears. On Linux, dmesg shows the enumeration, and a terminal returns what you type in uppercase:

Shell
screen /dev/ttyACM0 115200
Text
usb 1-1: new full-speed USB device number 12 using xhci_hcd
usb 1-1: New USB device found, idVendor=1209, idProduct=0001, bcdDevice= 1.00
usb 1-1: Product: STM32 Serial
cdc_acm 1-1:1.0: ttyACM0: USB ACM device
HELLO

What does each piece do? The interrupt handler hands the controller's events to the stack, which queues them. tud_task() runs the protocol engine: it processes the queued events, answers control requests on endpoint 0, calls the descriptor callbacks and moves data between the class buffers and the endpoints. The application reads and writes through the CDC buffers, never through the hardware. That division, interrupt feeds, task processes, application reads, is the structure of every TinyUSB program and of most other stacks.

The main-loop discipline

The stack has to be served promptly. During enumeration the host expects responses to control requests within a few milliseconds (the specification allows up to 50 ms for a data stage and 5 seconds for the whole of a request, and in practice, a stall of tens of milliseconds causes retries and failures on stricter hosts). A main loop that blocks for 100 ms on a sensor read or a printf to a slow UART looks to the host like a dead device. Keep every operation in the loop short, and where a task needs time, break it into steps or move it to a timer interrupt or an RTOS task.

With an RTOS, run the USB stack in its own task. TinyUSB has an OS abstraction layer for FreeRTOS: set CFG_TUSB_OS OPT_OS_FREERTOS, create a task whose body is tud_task() in a loop, and the stack blocks on a queue instead of spinning. The interrupt handler needs a priority at or below the highest priority from which FreeRTOS calls are allowed, or a ...FromISR call from it will assert.

The device also has states you should react to. Mount and unmount callbacks (tud_mount_cb, tud_umount_cb) tell you when the host has configured or dropped the device. Suspend (tud_suspend_cb) means the host has stopped sending frames for 3 ms; a bus-powered device must reduce its supply current to 2.5 mA or less within 10 ms, which in practice means stopping radios, LEDs and displays, and entering a low-power mode that a resume interrupt can end. Resume (tud_resume_cb) means the host is active again. A device that does not honor suspend can drain a laptop battery and fail certification.

Moving data: buffers, packets and throughput

Data moves in packets, and the details decide how much you get. A full-speed bulk endpoint carries 64 bytes per packet, and the host reads a transfer until it sees a packet shorter than the maximum size. A message that is an exact multiple of 64 bytes needs a zero-length packet to end it, a rule that has surprised everyone who has written a host program once. The class buffers in the stack (the CFG_TUD_CDC_RX_BUFSIZE and TX_BUFSIZE values above) decouple your code from the endpoints, and the right size depends on the burstiness of your data: a producer that writes 1 KB in a loop needs a transmit buffer that large, or the write returns short, and code that ignores the return value loses data.

The call that surprises the most people is tud_cdc_write, which returns how many bytes it accepted, not an error. If you pass 200 bytes and the buffer has room for 100, you get 100 back, and the rest is yours to resend. A reliable writer loops, calling tud_task() to let the buffer drain, and gives up if the host has gone away:

cdc_write_all.cc
static void cdc_write_all(const uint8_t *p, uint32_t n)
{
	while (n && tud_cdc_connected()) {
		uint32_t w = tud_cdc_write(p, n);

		p += w;
		n -= w;
		tud_cdc_write_flush();
		tud_task();
	}
}

Throughput is bounded by the bus. Full speed has 1 ms frames, and the specification allows at most 19 bulk transactions of 64 bytes in a frame, 1,216,000 bytes per second; the practical figure depends on the host controller, other devices on the bus and how well the firmware keeps the pipe full. To measure what your device actually achieves, make it stream data and time it on the host:

throughput.cc
#include <fcntl.h>
#include <stdio.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>

int main(void)
{
	int fd = open("/dev/ttyACM0", O_RDONLY | O_NOCTTY);
	struct termios t;
	unsigned char buf[4096];
	long total = 0;
	struct timespec a, b;

	if (fd < 0)
		return 1;
	tcgetattr(fd, &t);
	cfmakeraw(&t);
	tcsetattr(fd, TCSANOW, &t);

	clock_gettime(CLOCK_MONOTONIC, &a);
	do {
		ssize_t n = read(fd, buf, sizeof buf);
		if (n <= 0)
			break;
		total += n;
		clock_gettime(CLOCK_MONOTONIC, &b);
	} while ((b.tv_sec - a.tv_sec) < 10);

	double s = (b.tv_sec - a.tv_sec) + (b.tv_nsec - a.tv_nsec) / 1e9;
	printf("%.2f MB/s over %.1f s\n", total / s / 1e6, s);
	return 0;
}
Text
1.06 MB/s over 10.0 s

The number printed is an illustration of the form of the result. Run it with a device firmware loop that writes full 64-byte packets whenever there is space, and compare it with the 1.2 MB/s bus ceiling; a result near 60 kB/s means the firmware refills the buffer once per millisecond, and one near the ceiling means the pipe is full. This ten-line measurement is the best performance tool you have, and it turns "USB is slow" into "my write loop is the limit".

When it does not enumerate: a diagnostic order

Debug USB from the bottom up, because each layer depends on the one below.

SymptomLikely layerFirst checks
Nothing happens when plugged inElectricalVBUS present? D+ pull-up enabled? Connector soldered? dmesg shows no event
device descriptor read/64, error -71 or -110Clock or firmware not running48 MHz clock, VBUS sensing, firmware stuck, interrupts not enabled
Enumerates, then disconnects after a few secondsFirmware stallstud_task() not called often enough
"Unknown device" on Windows, fine on LinuxDriver bindingClass codes wrong; missing IAD; cached descriptor
Port appears, no dataApplicationDTR not set; buffers full; endpoint directions swapped
Works on a port, fails on a hubMarginal hardwareClock accuracy, ESD parts, inrush

The tools, in the order to reach for them: the host's kernel log (dmesg -w on Linux), lsusb -v to print the descriptors the host actually received (compare them with your source), TinyUSB's own log (set CFG_TUSB_DEBUG to 2 and print through a spare UART, and every control request and event appears), a protocol capture with usbmon and Wireshark on Linux, and, for the stubborn cases, a hardware USB analyzer, which sees the electrical bus and the retries that no software tool can. A cheap logic analyzer with a USB decoder is enough for most.

On Windows, the descriptor is cached against the vendor ID, product ID and serial number, so a changed descriptor with the same IDs may be ignored. Change the product ID during development whenever the layout changes. The "Unknown USB Device (Device Descriptor Request Failed)" message is the Windows version of error -71.

Updating the firmware over USB

A USB device should be able to update itself over the same port. The standard is DFU, Device Firmware Upgrade, in which a bootloader presents a DFU interface and accepts a new image. STM32 parts have a ROM bootloader that does DFU over USB on the OTG_FS pins when BOOT0 is high at reset; it enumerates as 0x0483:0xDF11 and dfu-util can program it. For a product without a BOOT0 button, the application adds a DFU runtime interface: when dfu-util sends a detach request, the application stores a flag and resets, and the bootloader starts. Other approaches in common use are the UF2 bootloader, where the device appears as a disk and the user drags a .uf2 file onto it (used by Adafruit and Raspberry Pi boards), and vendor-specific protocols over the serial port.

Whatever you choose, a bootloader is part of the product's safety. Verify the image (at least a CRC, better a signature) before it boots, keep a recovery path that a bad application cannot erase, and consider whether anyone with USB access should be able to replace the firmware at all. The post on the DFU runtime and detach covers the descriptors and the jump.

Compliance, identifiers and shipping

A prototype can use any identifiers; a product cannot. The vendor ID identifies the company that made the device, and using one you do not own is a violation of the USB-IF's terms and a cause of conflicts, since a driver binds to the pair. The options are to buy a vendor ID from the USB-IF (a yearly cost, with the right to use the USB logo after compliance testing), to license a product ID from a chip or board vendor that sells them, or, for open-source hardware, to take a product ID under 0x1209 from pid.codes. The logo and the "USB" name need USB-IF compliance testing; a product may work without it, but a retailer or an enterprise customer can insist.

The practical compliance points are the ones a firmware engineer controls: a unique serial number string per device, correct suspend current, a valid descriptor set, a response to every standard request, correct handling of SET_ADDRESS timing and clean behavior on reset. TinyUSB handles most of the protocol, and the hardware checklist covers the electrical side. Run the USB-IF's USB Command Verifier (USBCV) tool against the device on a Windows machine; it exercises the standard requests and catches the mistakes that make some hosts misbehave.

Talking to the device from the host

A firmware project has two halves, and the half on the host decides how the device feels to use. For a CDC serial port the host side is any terminal program, or code that opens /dev/ttyACM0 (COM5 on Windows) and reads and writes bytes. That is the lowest-effort path, and it carries the serial port's limits: no packet boundaries, no error reporting beyond what your protocol adds, and a line discipline in the operating system that may translate line endings and echo characters unless you put the port in raw mode with stty raw -echo or cfmakeraw. For a HID device the host side is the operating system itself: the device appears as an input device, and applications read events from the input subsystem. A generic HID device with custom reports is reached through hidapi, a portable library with the same API on Linux, macOS and Windows.

For a vendor-specific interface the host side is libusb, which gives a program direct access to the endpoints. It needs a permission rule on Linux (a udev rule that grants your user access), nothing on macOS, and WinUSB on Windows, which the Microsoft OS 2.0 descriptors install automatically. A program that opens the device, claims the interface and calls libusb_bulk_transfer is about forty lines. The choice among these is the choice of how much protocol you want to own. A serial port with a line-based text protocol is the easiest to debug, since a person can type commands into a terminal. A vendor interface with binary messages is faster and more reliable, and costs a host program.

Whichever you choose, design the protocol with three properties. It must recover from a lost or half-sent message, which means framing: a length field, or a delimiter and an escape. It must identify itself and its version in the first exchange, so a new host program can detect an old device. And it must be testable without the device, by having the firmware's protocol code compile on a host machine against a fake transport, so that the parser is exercised by unit tests and not only by hardware.

Power management: current, suspend and wakeup

USB is a power source as well as a data link, and a device is judged on how it behaves as one. The rules, from the USB 2.0 specification, are short. Before configuration a device may draw at most 100 mA from VBUS. After the host configures it, up to the value in bMaxPower of the configuration descriptor, to a maximum of 500 mA at USB 2.0 (a host or hub port may refuse a configuration that asks for more than it can give). In suspend, a bus-powered device must draw no more than 2.5 mA, within 10 ms of the bus going idle.

Three practical consequences follow. First, declare the current honestly. A device that draws 300 mA with a radio on but declares 100 mA works on a strong port and browns out on a weak one, and the failure appears as random resets that nobody can reproduce on the bench. Second, bring the high-current parts up after configuration, not at power-on, so that the unconfigured limit holds. Third, implement suspend: in tud_suspend_cb, turn off the displays, radios and peripheral clocks you can, and enter a low-power state from which the USB resume signal can wake the core. If the device has remote wakeup (a keyboard that wakes a sleeping computer), declare it in bmAttributes, check that the host enabled it (the argument of the suspend callback), and call tud_remote_wakeup() on the event.

Inrush is the fourth. A host port cannot supply a surge to charge a large capacitor at attach; the specification limits the capacitance a device may present to 10 microfarads without a soft start. A device with a bulk capacitor of 100 microfarads and no inrush control causes hubs to disconnect it, and a power-limited hub port to shut off. A load switch with a slow turn-on, or a series resistor that is bypassed after startup, solves it.

Mistakes that appear in almost every first project

After a few USB projects, the same errors recur, and a list of them is worth keeping.

  • Declaring endpoint directions backwards. IN is from the host's point of view. An interface whose firmware writes to an OUT endpoint never delivers data.

  • Using one endpoint number for two functions. Two interrupt IN endpoints on number 1 collide. Number every IN and every OUT endpoint uniquely.

  • Forgetting the return value of write calls. A short write is a normal result. Loop until everything is queued, or drop data deliberately and count it.

  • Printing before the host is listening. The first lines vanish. Wait for the line state or the mount event, or buffer the output.

  • Blocking in the main loop. Any wait longer than a few milliseconds without tud_task() risks a timeout during enumeration.

  • Assuming descriptors are reread. Hosts cache them. Change the product ID or the serial number while you iterate.

  • Hard-coding the serial number. Two boards with the same one confuse the host's driver database, and Windows assigns a COM port by serial number, so every board reuses the same port.

  • Ignoring suspend. The product works on the bench and fails a battery-life or compliance test.

  • Mixing up bytes and bits in descriptors. bMaxPower is in units of 2 mA, wMaxPacketSize in bytes, bInterval in milliseconds at full speed and in units of 125 microseconds, as a power of two, at high speed.

A useful discipline is to keep the descriptors in one file, with one comment per line, and to read them against the specification once, slowly, before the first time you plug the device in. It takes half an hour, and it removes a class of bugs that would otherwise cost several days across the first few boards.

A short reading list for the specification

You do not need to read the whole of the USB 2.0 specification, which runs to about 650 pages, but three parts repay the effort. Chapter 9, "USB Device Framework", defines the standard requests and every descriptor field, and is the reference to open when a host rejects a descriptor. Chapter 5, "USB Data Flow Model", explains frames, transfer types and the bandwidth rules behind the throughput limits. Chapter 7 covers the electrical signaling, and matters when you design the board. Each class has its own short document (the CDC, HID, mass storage, MIDI and DFU specifications from the USB-IF, a few dozen pages each) and the one for the class you implement is worth reading in full once. When a stack's behavior looks wrong, the specification settles the argument faster than any forum thread, because the host operating systems implement it closely and your device will be judged against it.

Where to go next

This guide is the hub of a ladder of posts on this site. The descriptors, endpoints and enumeration sequence are explained byte by byte in their own post. For specific devices there are posts on a Raspberry Pi Pico serial port, an STM32 virtual COM port, a USB keyboard on the RP2040, a CDC device on the ESP32-S3, MIDI, a mass storage drive from flash, a vendor-specific interface with libusb, and a Windows driverless device with Microsoft OS 2.0 descriptors. The deeper posts cover the DTR line state, custom HID report descriptors for a gamepad, composite devices, full-speed bulk throughput, DFU runtime and detach, and a hardware design checklist, plus a comparison of stacks and a Rust implementation with usb-device. Start with the descriptors post if you are new to USB, with the stack comparison if you are choosing, and with the diagnostic table above if something already fails.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.