Embedded HandbookApps
All sections › III. Peripherals
STM32F103, STM32F411, STM32G431, STM32H743 · level intermediate · 16 min read
Open in the interactive handbook

20е. TinyUSB: an open USB device and host stack instead of the ST library

In section 20 the device became a COM port on the ST library, in 20в a keyboard, in 20д a device of its own class with descriptors byte by byte. All of that rested on ST code: the USB Device Library from CubeMX or, on newer series, USBX. It works, but it is tied to STM32 and to HAL, and a composite device on it is assembled by hand — by editing someone else's files.

TinyUSB is an open USB stack that lives separately from the chip vendor. The same device code builds for STM32 F0, F1, F4, G4, H7, U5, for ESP32-S2 and S3, RP2040, nRF52 and dozens of other families. MIT licence, no dynamic memory at all, the CDC, HID, MSC, MIDI, audio, DFU and vendor classes are already written. The USB parts of CircuitPython and of the Arduino cores for RP2040 and ESP32 are built on it — so the code is proven on millions of boards.

This section covers: why and when to choose TinyUSB; how it is layered; the tusb_config.h settings file; descriptors via callbacks; the main loop and the interrupt; a CDC COM port; a HID keyboard; a composite CDC + HID with a Python model of the descriptor; MSC storage and host mode briefly; running under FreeRTOS; a comparison with the ST libraries; pitfalls.

What is not repeated here: the bus itself, enumeration and the CDC class — 20; the OTG host on the ST library — 20а; the report descriptor language and key codes — 20в; the bytes of standard descriptors, BOS and WinUSB — 20д; DFU — 48л.

Sources (topics only): the TinyUSB sources and examples (the src/ and examples/device/ directories), the USB 2.0, CDC 1.2 and HID 1.11 specifications and the USB-IF note on the Interface Association Descriptor. Function names are given from memory of the 0.1x branch and need checking against your version.

What it is called in the documentation

Original Meaning
TinyUSB device stack (usbd) the TinyUSB device core
class driver (cdc_device, hid_device, msc_device) a class driver in TinyUSB
DCD, device controller driver the stack's port to a specific USB block of the chip
HCD, host controller driver the host stack's port to the USB block
tusb_config.h the TinyUSB settings file in the project
tud_task, tud_int_handler the device event loop and the entry from the USB interrupt
rhport (root hub port) the number of the chip's USB port in TinyUSB calls
descriptor callbacks callbacks that return descriptors

20е.1 Why TinyUSB and when you do not need it

TinyUSB is chosen when:

It is not needed when the project is already on CubeMX, there is one class, and the device will not leave STM32: the ST library is generated with a mouse and familiar to the whole team. And when you need a certified stack with a vendor guarantee — TinyUSB is an open project without one.

How big it is. On Cortex-M with -Os a CDC device takes roughly 10–15 KB of flash and 2–3 KB of RAM including buffers — the same order as the ST USB Device Library. This is an estimate from memory, not a measurement: the size depends strongly on the number of classes and buffer sizes.

20е.2 Stack layers

TinyUSB layers: at the top the application callbacks (descriptors, data reception, events); below them the CDC, HID, MSC, vendor class drivers; under them the usbd device core with endpoint 0 handling and the event queue; further down the DCD port — stm32_fsdev for the USB FS block of F0/F1/G4 and dwc2 for OTG on F4/F7/H7/U5; at the very bottom the chip's USB block. On the right two contexts: the USB interrupt calls tud_int_handler and only puts an event into the queue, while tud_task in the main loop or a task drains the queue and calls the class drivers

From the bottom up:

  1. The chip's USB block. STM32 has two kinds: USB FS "device" with PMA memory (F0, F1, F3, G0, G4, L0, L4 without OTG) and OTG on the Synopsys DWC2 core (F2, F4, F7, H7, L4+, U5).
  2. The DCD port. A thin layer that knows the block's registers: open an endpoint, queue a transfer, report completion. For the first kind — the stm32_fsdev port, for the second — the common dwc2, the same one used on ESP32-S2/S3. This is the only place where TinyUSB depends on the chip.
  3. The usbd core. Enumeration, endpoint 0, standard requests, parsing the configuration descriptor and handing interfaces to the class drivers.
  4. Class drivers. CDC, HID, MSC, MIDI, audio, DFU, vendor and others. Each is enabled by its own CFG_TUD_... and gives the application a simple API.
  5. The application. Callbacks with the tud_..._cb prefix: descriptors, connection events, data reception.

Two contexts. The USB interrupt processes nothing itself: the DCD port writes an event into the queue and returns. All the work — answering requests, calling classes and your callbacks — is done by tud_task(), called from the main loop or from an RTOS task. So TinyUSB callbacks do not run in the interrupt: you may call almost anything in them, but you must not stall the loop for long.

20е.3 The tusb_config.h file

The stack is configured by one header in the project. The minimum for an F411 with a COM port and a keyboard:

/* tusb_config.h */
#define CFG_TUSB_MCU            OPT_MCU_STM32F4
#define CFG_TUSB_OS             OPT_OS_NONE      /* или OPT_OS_FREERTOS */
#define CFG_TUSB_DEBUG          0

#define CFG_TUD_ENABLED         1                /* режим устройства */
#define CFG_TUD_MAX_SPEED       OPT_MODE_FULL_SPEED
#define CFG_TUD_ENDPOINT0_SIZE  64

#define CFG_TUD_CDC             1                /* число интерфейсов CDC */
#define CFG_TUD_HID             1
#define CFG_TUD_MSC             0
#define CFG_TUD_VENDOR          0

#define CFG_TUD_CDC_RX_BUFSIZE  256              /* кольцевые буферы CDC */
#define CFG_TUD_CDC_TX_BUFSIZE  256
#define CFG_TUD_CDC_EP_BUFSIZE  64
#define CFG_TUD_HID_EP_BUFSIZE  8

/* выравнивание и размещение буферов для DMA, если нужно */
#define CFG_TUSB_MEM_SECTION
#define CFG_TUSB_MEM_ALIGN      __attribute__((aligned(4)))

What matters:

20е.4 Descriptors via callbacks

The stack does not store descriptors itself: it asks the application for them when the host issues GET_DESCRIPTOR. Three mandatory functions:

#include "tusb.h"

tusb_desc_device_t const desc_device = {
    .bLength            = sizeof(tusb_desc_device_t),
    .bDescriptorType    = TUSB_DESC_DEVICE,
    .bcdUSB             = 0x0200,
    .bDeviceClass       = TUSB_CLASS_MISC,       /* 0xEF: составное с IAD */
    .bDeviceSubClass    = MISC_SUBCLASS_COMMON,  /* 0x02 */
    .bDeviceProtocol    = MISC_PROTOCOL_IAD,     /* 0x01 */
    .bMaxPacketSize0    = CFG_TUD_ENDPOINT0_SIZE,
    .idVendor           = 0x1209,                /* тестовый VID pid.codes */
    .idProduct          = 0x0001,
    .bcdDevice          = 0x0100,
    .iManufacturer      = 1,
    .iProduct           = 2,
    .iSerialNumber      = 3,
    .bNumConfigurations = 1,
};

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

uint8_t const *tud_descriptor_configuration_cb(uint8_t index) {
    (void)index;
    return desc_config;                          /* см. 20е.7 */
}

static uint16_t str_buf[32];
static char const *const strings[] = { "", "Example", "CDC+HID", "0001", "CDC", "Keyboard" };

uint16_t const *tud_descriptor_string_cb(uint8_t index, uint16_t langid) {
    (void)langid;
    uint8_t n;
    if (index == 0) {
        str_buf[1] = 0x0409;                     /* английский (США) */
        n = 1;
    } else {
        if (index >= sizeof strings / sizeof strings[0]) return NULL;
        char const *s = strings[index];
        for (n = 0; s[n] && n < 31; n++) str_buf[1 + n] = s[n];
    }
    str_buf[0] = (uint16_t)((TUSB_DESC_STRING << 8) | (2 * n + 2));
    return str_buf;
}

A string is returned in UTF-16: the first word is the type and the length in bytes. Index 0 is the language list. The serial number is best built from the chip's unique ID (UID), otherwise Windows treats all boards as one.

20е.5 The main loop and the interrupt

int main(void) {
    board_init();                 /* такты: 48 МГц на USB, выводы PA11/PA12 */
    tud_init(0);                  /* порт 0; в старых версиях tusb_init() */
    for (;;) {
        tud_task();               /* разбирает очередь событий USB */
        cdc_task();
        hid_task();
    }
}

/* F411: блок OTG_FS */
void OTG_FS_IRQHandler(void) {
    tud_int_handler(0);
}
/* F103: блок USB FS — три вектора, все в одну функцию */
void USB_HP_CAN1_TX_IRQHandler(void)  { tud_int_handler(0); }
void USB_LP_CAN1_RX0_IRQHandler(void) { tud_int_handler(0); }
void USBWakeUp_IRQHandler(void)       { tud_int_handler(0); }

Names changed between versions: in old branches the handler was called dcd_int_handler(rhport), and initialisation was tusb_init() without arguments. Look at the examples/device/cdc_msc example of your version and take the names from there.

What board_init() does in the TinyUSB examples you will have to do yourself: set up 48 MHz for USB (section 20), enable the clock of the block and GPIO, put the pins into the alternate function, enable the interrupt in the NVIC. TinyUSB does not deal with clocks.

20е.6 COM port and keyboard

CDC. Echo with confirmation:

void cdc_task(void) {
    if (!tud_cdc_connected()) return;            /* терминал выставил DTR */
    if (tud_cdc_available()) {
        uint8_t buf[64];
        uint32_t n = tud_cdc_read(buf, sizeof buf);
        tud_cdc_write(buf, n);
        tud_cdc_write_flush();                   /* без этого данные ждут */
    }
}

void tud_cdc_line_coding_cb(uint8_t itf, cdc_line_coding_t const *lc) {
    (void)itf;
    if (lc->bit_rate == 1200) enter_bootloader();  /* приём Arduino: 1200 бод */
}

tud_cdc_write puts bytes into a ring buffer and sends them only when a full packet has accumulated. A tail shorter than 64 bytes leaves only after tud_cdc_write_flush(). With several interfaces — the same functions with the tud_cdc_n_ prefix and an instance number.

HID. A boot-protocol keyboard, as in 20в:

uint8_t const desc_hid_report[] = { TUD_HID_REPORT_DESC_KEYBOARD() };

uint8_t const *tud_hid_descriptor_report_cb(uint8_t instance) {
    (void)instance;
    return desc_hid_report;
}

void hid_task(void) {
    static uint32_t t;
    static bool pressed;
    if (board_millis() - t < 10 || !tud_hid_ready()) return;
    t = board_millis();
    bool btn = button_read();
    if (btn != pressed) {
        uint8_t keys[6] = { btn ? HID_KEY_A : 0 };
        tud_hid_keyboard_report(0, 0, keys);     /* номер отчёта 0, без модификаторов */
        pressed = btn;
    }
}

/* обязательные, даже если не нужны */
uint16_t tud_hid_get_report_cb(uint8_t i, uint8_t id, hid_report_type_t t, uint8_t *b, uint16_t n)
{ (void)i; (void)id; (void)t; (void)b; (void)n; return 0; }
void tud_hid_set_report_cb(uint8_t i, uint8_t id, hid_report_type_t t, uint8_t const *b, uint16_t n)
{ (void)i; (void)id; (void)t; (void)b; (void)n; }  /* сюда приходят светодиоды Caps Lock */

A report is sent only on change: the press, then the release with an empty array. tud_hid_ready() checks that the previous report has already been taken by the host.

20е.7 Composite CDC + HID: the descriptor and its model

In TinyUSB the configuration descriptor is assembled from macros — each expands into the required number of bytes:

enum { ITF_CDC = 0, ITF_CDC_DATA, ITF_HID, ITF_TOTAL };
#define EP_CDC_NOTIF  0x81
#define EP_CDC_OUT    0x02
#define EP_CDC_IN     0x82
#define EP_HID_IN     0x83
#define CONFIG_LEN    (TUD_CONFIG_DESC_LEN + TUD_CDC_DESC_LEN + TUD_HID_DESC_LEN)

uint8_t const desc_config[] = {
    TUD_CONFIG_DESCRIPTOR(1, ITF_TOTAL, 0, CONFIG_LEN, 0x80, 100),
    TUD_CDC_DESCRIPTOR(ITF_CDC, 4, EP_CDC_NOTIF, 8, EP_CDC_OUT, EP_CDC_IN, 64),
    TUD_HID_DESCRIPTOR(ITF_HID, 5, HID_ITF_PROTOCOL_KEYBOARD,
                       sizeof(desc_hid_report), EP_HID_IN, CFG_TUD_HID_EP_BUFSIZE, 10),
};

TUD_CDC_DESCRIPTOR occupies two interfaces — control and data — and itself inserts an IAD before them, binding them into one function. Without the IAD Windows will not understand that interfaces 0 and 1 are one COM port. Hence the class 0xEF/0x02/0x01 in the device descriptor from 20е.4.

So as not to take the macros on trust, the model20g.py model builds the same bytes from the fields of the USB, CDC and HID specifications, and then parses the result the way the host does: it walks the length field of each descriptor, counts interfaces and endpoints, looks for the IAD. Block lengths:

block length
TUD_CONFIG_DESCRIPTOR 9
TUD_CDC_DESCRIPTOR (with IAD) 66
TUD_HID_DESCRIPTOR 25
TUD_MSC_DESCRIPTOR 23
keyboard report 65

The CDC block: IAD 8 bytes, control interface 9, four functional descriptors 5 + 5 + 4 + 5, notification endpoint 7, data interface 9 and two bulk endpoints of 7 each. The keyboard report in the model is the one from 20в, with two-byte key code range fields; the report length of the TUD_HID_REPORT_DESC_KEYBOARD macro in your version may differ by a couple of bytes, so it goes into the descriptor via sizeof, not as a number.

Parsing the assembled composite descriptor:

field value
wTotalLength 100 = 9 + 66 + 25
bNumInterfaces 3
interfaces 0, 1, 2
endpoints 0x81, 0x02, 0x82, 0x83
IAD first 0, count 2

In total 100 bytes, three interfaces in a row without gaps, four endpoints, each IN one with its own number. If you forget TUD_HID_DESC_LEN in CONFIG_LEN, the length field will hold 75: the host reads 75 bytes and does not see the 25 HID bytes — the keyboard silently disappears. The CDC + MSC variant instead of HID gives 98 bytes.

Endpoint numbers: OUT 0x02 and IN 0x82 are different endpoints, and they may share one number. But two IN endpoints with the same number are an error. The USB FS block of the F103 has only 8 endpoint pairs and 512 bytes of PMA, the OTG_FS of the F411 has 4 IN and 4 OUT endpoints (including endpoint zero) and 1.25 KB of FIFO: CDC + HID + MSC already just fits the F411's endpoints.

20е.8 Storage, host and FreeRTOS briefly

MSC. CFG_TUD_MSC 1, a TUD_MSC_DESCRIPTOR block in the configuration and callbacks: tud_msc_inquiry_cb (device name), tud_msc_capacity_cb (number and size of blocks), tud_msc_read10_cb and tud_msc_write10_cb (reading and writing a block by LBA), tud_msc_scsi_cb for other SCSI commands. The medium may be an array in flash with a ready FAT — this is how a "disk with instructions" is made — or an SD card.

Host. The same stack with the tuh_ prefix: CFG_TUH_ENABLED 1, the classes CFG_TUH_HID, CFG_TUH_MSC, CFG_TUH_CDC, the hub CFG_TUH_HUB; the loop is tuh_task(), the interrupt is tuh_int_handler(). The application receives the events tuh_mount_cb, tuh_hid_report_received_cb and so on. On STM32 the host works through the same dwc2 port on OTG; the USB FS block of the F103 cannot be a host. Host support on STM32 is younger than device mode — check your version.

FreeRTOS. CFG_TUSB_OS OPT_OS_FREERTOS: the event queue becomes a FreeRTOS queue, and tud_task() sleeps while there are no events. A separate task:

static void usb_thread(void *arg) {
    (void)arg;
    tud_init(0);
    for (;;) tud_task();          /* блокируется на очереди */
}
/* xTaskCreate(usb_thread, "usb", 512, NULL, configMAX_PRIORITIES - 2, NULL); */

The USB interrupt priority must be no higher than configMAX_SYSCALL_INTERRUPT_PRIORITY (numerically not lower), otherwise a queue call from the interrupt will break the kernel. Call tud_cdc_write and tud_hid_report from one task or protect them with a mutex: the stack is not designed for simultaneous access from several tasks to one interface.

20е.9 Comparison with the ST libraries

ST USB Device Library USBX (Azure RTOS / Eclipse ThreadX) TinyUSB
licence ST's own licence (SLA) MIT since the Eclipse version MIT
chips STM32 only any, ST ports for newer series dozens of families from different vendors
HAL dependency on HAL PCD on HAL PCD in ST packages its own, no HAL needed
memory static, by editing templates ThreadX memory pool static only
composite device by hand, editing class files built in built in, via flags and macros
host a separate library built in built in, younger than device mode
CDC device size roughly 10–15 KB roughly 20–30 KB roughly 10–15 KB

The sizes in the last row are orders of magnitude from memory, not measurements, and depend on the number of classes, buffers and optimisation. USBX is stronger for complex host setups and certification; the ST library comes "out of the box" in CubeMX; TinyUSB — when portability and composite devices matter.

20е.10 Pitfalls

The device is not recognised on an F4 with OTG. The block waits for voltage on VBUS (PA9), and on the board it is not routed there. Disable VBUS sensing — the NOVBUSSENS bit in GCCFG on F405/F407, VBDEN on F411/F446 (the bits have opposite meaning) — or route VBUS to the pin. Recent TinyUSB versions have a setting for this; in old ones the dwc2 port was edited by hand.

Not 48 MHz. USB requires 48 MHz ±0.25%: from a crystal via the PLL or from HSI48 trimmed by CRS on SOF frames (G4, L4, U5). An internal RC without trimming on F1 and F4 will not do — the device is found sometimes and sometimes not.

Data reaches the COM port late or not at all. You forgot tud_cdc_write_flush(). Also: the terminal did not assert DTR, and the code waits for tud_cdc_connected().

One of the classes disappeared. wTotalLength does not match the sum of the block lengths, or ITF_TOTAL is less than the real number of interfaces (CDC counts as two). Compute the length as an expression of ..._DESC_LEN, not as a number.

You changed the class or the set of interfaces — and Windows sees the old one. The system remembers the device by the VID/PID pair (and serial number) and does not re-read the descriptors. During development change idProduct or bcdDevice every time the set changes, or remove the device in Device Manager together with its driver.

A callback held the loop for long. tud_task() is not called — the host gets no answers on endpoint 0 and resets the device after a few seconds. Move long work out of callbacks.

Two versions of examples. Code from an old article does not build: these changed — tusb_init → tud_init(rhport), dcd_int_handler → tud_int_handler, CFG_TUSB_RHPORT0_MODE → CFG_TUD_ENABLED. Take examples from the same release as the stack.

20е.11 Summary

Next: section 21 "SWO and ITM" — debug output that takes neither a UART nor a single pin beyond those already used by the debugger.

Open in the interactive handbook