Build a USB CDC Virtual COM Port on STM32 With TinyUSB
Bring up a USB CDC serial port on an STM32F4 with TinyUSB: 48 MHz clock, OTG_FS pins, VBUS sensing, the interrupt handler, tusb_config.h and a printf retarget.

A virtual COM port is the most useful thing a microcontroller can do over USB: a log console, a command shell, a firmware-update channel and a data pipe, with no driver needed on the host. On the STM32F4 the USB full-speed device controller is the Synopsys OTG_FS core, and TinyUSB supports it with its dcd_synopsys driver. The descriptors and the application loop are the same as on any other chip (the Pico post of this series shows them); what is specific to STM32 is the clock tree, the pins, the VBUS detection and the interrupt wiring, and those are where a first attempt fails. This post brings up CDC on an STM32F407 Discovery-class board with TinyUSB 0.17 and no ST middleware, using the registers and CMSIS definitions from stm32f4xx.h. The hardware details are from RM0090 (USB on-the-go full-speed chapter).
The 48 MHz clock requirement
The USB full-speed PHY needs a 48 MHz clock accurate to about 0.25 percent, and it cannot come from the high-speed internal RC oscillator. On the F4 it comes from the main PLL's Q output (PLLQ). With an 8 MHz crystal, the usual 168 MHz configuration is PLLM = 8, PLLN = 336, PLLP = 2 and PLLQ = 7: the VCO runs at 8 / 8 * 336 = 336 MHz, the system clock is 336 / 2 = 168 MHz and the USB clock is 336 / 7 = 48 MHz. If you pick a system clock for which no PLLQ gives exactly 48 MHz, you have a choice between giving up the clock speed and using the separate PLLI2S output as the USB source (not available on every F4 package), so choose the system clock with USB in mind from the start. The ST HAL clock functions can set this, or you can write RCC->PLLCFGR directly. A device whose USB clock is wrong enumerates erratically or not at all, and the symptom in the host log is device descriptor read/64, error -71 or -110.
Pins and alternate function
On the F4 the OTG_FS signals sit on PA11 (OTG_FS_DM, D-) and PA12 (OTG_FS_DP, D+), both alternate function 10, with no pull-up or pull-down: the controller has its own internal pull-up on D+ for full-speed attach. VBUS sensing uses PA9, and the ID pin for host mode is PA10; a device-only design does not need either.
#include "stm32f4xx.h"
void usb_gpio_init(void)
{
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
/* PA11 and PA12: alternate function, very high speed, AF10 */
GPIOA->MODER &= ~((3u << 22) | (3u << 24));
GPIOA->MODER |= ((2u << 22) | (2u << 24));
GPIOA->OSPEEDR |= ((3u << 22) | (3u << 24));
GPIOA->PUPDR &= ~((3u << 22) | (3u << 24));
GPIOA->AFR[1] &= ~((0xFu << 12) | (0xFu << 16));
GPIOA->AFR[1] |= ((10u << 12) | (10u << 16));
RCC->AHB2ENR |= RCC_AHB2ENR_OTGFSEN;
}PA11 and PA12 are bits 22 to 25 of MODER and bits 12 to 19 of AFR[1] (pins 8 to 15 live in the high register at four bits per pin), which is why the shifts are 12 and 16. The OTG_FS peripheral clock is enabled through AHB2ENR.
VBUS sensing
By default the core wants to see VBUS on PA9 to know a host is attached. On a board where PA9 is not connected to VBUS, the device would never connect. TinyUSB's STM32 board support disables sensing and tells the core that VBUS is always valid:
void usb_disable_vbus_sensing(void)
{
USB_OTG_FS->GCCFG &= ~(USB_OTG_GCCFG_VBUSBSEN | USB_OTG_GCCFG_VBUSASEN);
USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_NOVBUSSENS;
}Self-powered devices that must notice a cable being removed, so as to detach cleanly and save power, do the opposite: wire VBUS through a divider to PA9, set VBUSBSEN and leave NOVBUSSENS clear. A bus-powered device loses power when VBUS goes away, so it does not need sensing. A device that does not disable sensing on a board with PA9 floating enumerates on some hosts and not on others, which is a maddening symptom: check this register first when behavior varies.
The interrupt
TinyUSB does all USB processing in the interrupt handler through one entry point:
#include "tusb.h"
void OTG_FS_IRQHandler(void)
{
tud_int_handler(0);
}The handler name is the one in the startup file's vector table, and the NVIC must enable it: NVIC_SetPriority(OTG_FS_IRQn, 5); NVIC_EnableIRQ(OTG_FS_IRQn); with a priority that does not preempt anything that needs to be faster. The interrupt only queues events; tud_task() in the main loop processes them, which is why the loop must run frequently and the USB handler stays short.
TinyUSB configuration
tusb_config.h for this chip differs from the RP2040 one in the MCU and in the buffer sizes. The core has a shared FIFO RAM of 1.25 KB, which limits what you can configure:
#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 64CFG_TUD_CDC_EP_BUFSIZE is the size of the bulk endpoint packet, 64 bytes at full speed. The ring buffer sizes are free: larger transmit buffers let the program write bursts without waiting for the host. The descriptor callbacks are the same three as in the Pico example, with the serial number built from the chip's unique ID at address 0x1FFF7A10 (96 bits), which gives every board a distinct serial.
The main loop and printf
#include <stdio.h>
#include "tusb.h"
extern void system_clock_168mhz(void);
extern void usb_gpio_init(void);
extern void usb_disable_vbus_sensing(void);
int _write(int fd, const char *buf, int len)
{
(void)fd;
if (!tud_cdc_connected())
return len; /* drop output when nobody listens */
int sent = 0;
while (sent < len) {
uint32_t n = tud_cdc_write(buf + sent, (uint32_t)(len - sent));
sent += (int)n;
tud_cdc_write_flush();
tud_task();
}
return len;
}
int main(void)
{
system_clock_168mhz();
usb_gpio_init();
usb_disable_vbus_sensing();
NVIC_SetPriority(OTG_FS_IRQn, 5);
NVIC_EnableIRQ(OTG_FS_IRQn);
tusb_init();
uint32_t next = 0;
unsigned n = 0;
for (;;) {
tud_task();
if (tud_cdc_available()) {
char c;
tud_cdc_read(&c, 1);
tud_cdc_write_char(c);
tud_cdc_write_flush();
}
if (HAL_GetTick() >= next) { /* any 1 ms tick source */
next += 1000;
printf("uptime %u s\r\n", ++n);
}
}
}uptime 1 s
uptime 2 s
uptime 3 sThe _write function is what newlib's printf calls, so overriding it with the _write shown makes every printf go to the USB port; it needs -specs=nosys.specs or your own syscalls in the link. Calling tud_task() inside _write while waiting for buffer space lets the transmit queue drain, and returning early when tud_cdc_connected() is false stops a program with no terminal attached from blocking forever. Keep printf out of interrupt handlers: it is not reentrant and it calls tud_task().
Throughput and what limits it
Full-speed USB is 12 Mbit/s on the wire, and a bulk endpoint can move at most 19 packets of 64 bytes per 1 ms frame when the bus is otherwise idle, about 1.2 MB/s of payload in the best case (USB 2.0 specification, bulk transfer limits for full-speed). Real CDC rates are lower, because the host and the device must both keep the pipe full, and they are bounded by how fast the firmware refills the transmit buffer. The way to get close to the limit is to write in multiples of 64 bytes, keep the ring buffer large and call tud_task() at least once per millisecond.
Common problems
Enumeration fails with error -71. Check the 48 MHz clock, the VBUS sensing setting and the pull-up on D+. On custom boards the 1.5 kilo-ohm pull-up on D+ is internal to the core only if DCTL soft disconnect is cleared by the driver; an external one is wrong unless GPIO-controlled. Port appears and data does not flow. The program does not call tud_task() or the interrupt is not enabled. Works on a hub, fails on a direct port. Marginal clock accuracy, or a ground and shield issue; test with the crystal rather than an RC source. The host ignores the first output. Wait for tud_cdc_connected().


