Home ▸ STM32 Tutorials ▸ USB Tutorials ▸ CDC: Virtual COM Port

STM32 USB CDC Tutorial: Virtual COM Port with Transmit, Receive and printf

Many STM32 projects use a USB to UART bridge only to get serial data to a PC. USB CDC (Communication Device Class) removes that part, because the USB peripheral of the STM32 can appear on the PC as a virtual COM port over a single cable. This is Part 1 of the STM32 USB series.

In this tutorial you will set up the USB device in CDC mode with STM32CubeMX, send text to a serial terminal, receive commands that switch an LED, and redirect printf to USB. The tutorial also explains why a Blue Pill needs to be unplugged after flashing while an F446 board does not. If your board only offers a serial port through the ST-Link, the STM32 UART transmit tutorial shows that route, and if you are new to CubeMX, begin with Getting Started with STM32. The next parts of the series cover the USB HID gamepad and the CDC and HID composite class.

STM32 USB CDC Basics

USB CDC stands for Communication Device Class, a standard USB class that lets a microcontroller appear on the host computer as a serial port. Linux and macOS load the driver automatically, and Windows 10 and later include one as well, so the device shows up as a COM port that any serial terminal can open.

Compared with a UART connection, USB CDC needs no bridge chip and no second cable, because the USB peripheral of the STM32 handles the whole link. The baud rate selected in the serial terminal has no effect, since the transfer speed is set by the USB protocol and not by a baud rate divider.


STM32 USB CDC Board Support

Not every STM32 board gives you a USB connector that your own firmware can use, and this is a common source of confusion.

Custom boards such as the WeAct Studio F446 board used here, the DevEBox H7 board and the Blue Pill have a USB connector that is wired to the USB pins of the microcontroller, so it is free for your own code.

WeAct Studio STM32F446 development board with a USB-C connector used for USB CDC
WeAct Studio Dev Board
DevEBox STM32H7 development board with a single user USB connector
DevEbox Dev board
STM32 Blue Pill board with a USB connector for device-mode USB
Bluepill Dev Board

On a Nucleo-64 board the USB connector belongs to the ST-Link, so it cannot be used for the USB peripheral of the target microcontroller. A serial connection through the ST-Link is still possible with a UART, as described in the UART tutorials, but that is a different mechanism from USB CDC. Nucleo-144 boards and some Discovery boards add a second User USB connector that is free for your own code.

STM32 Nucleo-64 board whose USB connector is reserved for the ST-Link
Nucleo-64
STM32 Nucleo-144 board with a separate user USB connector
Nucleo-144

STM32 USB OTG FS vs HS

The STM32F446 has two USB peripherals, USB OTG FS (Full Speed) at 12 Mbit/s and USB OTG HS (High Speed) at up to 480 Mbit/s. The High Speed mode needs an external PHY chip. Without one, the HS peripheral can still run at Full Speed through its internal PHY, but it then uses PB14 and PB15, which do not match the connector of most custom boards.

The WeAct Studio board wires its connector to PA11 and PA12, so this series uses the OTG FS peripheral. It is also the USB peripheral that is available on the largest number of STM32 families.


STM32 USB CDC Wiring and Pins

The only connection needed is a USB cable between the board and the PC, and the cable must carry data because charge-only cables have no data lines.

STM32 pinUSB signalNote
PA11D− (USB_DM)Fixed by the USB OTG FS peripheral
PA12D+ (USB_DP)Fixed by the USB OTG FS peripheral
PB2LED outputOnboard LED of the WeAct board, used in the receive example
WeAct Studio STM32F446 schematic with the USB-C data lines on PA11 and PA12 and the LED on PB2

If you use another board, check two things in its schematic. First, confirm which pins the connector uses. PA11 and PA12 belong to the OTG FS peripheral, while PB14 and PB15 belong to the internal HS PHY. Second, confirm that the board has an external crystal, because the USB peripheral needs a 48 MHz clock that is accurate to roughly 0.25 %, which an internal RC oscillator usually cannot provide.


STM32 USB CDC CubeMX Configuration

Enable USB_OTG_FS (or USB Device FS on boards such as the Blue Pill) and select Device_Only mode, because the STM32 acts as a device connected to a PC. CubeMX then assigns PA11 and PA12 as the USB data lines. Keep the optional features, such as low power mode, VBUS sensing and SOF output, disabled for this basic setup.

STM32CubeMX USB OTG FS settings in Device Only mode with PA11 and PA12 assigned

Then open Middleware and set the USB Device class to Communication Device Class (Virtual Port Com). The RX and TX buffer sizes were reduced from 2048 to 512 bytes here, since this tutorial does not move large amounts of data.

STM32CubeMX middleware settings with the USB device class set to CDC and 512 byte buffers
  • Max number of configurations: keep 1, because more are needed only for composite devices.
  • Max number of interfaces: keep 1 for now.
  • USB self-powered: enabled, because the board has its own power supply.

Finally, configure PB2 as a GPIO output for the LED.

STM32CubeMX GPIO settings with PB2 configured as an output for the onboard LED

In the Project Manager tab, enter a project name, select STM32CubeIDE as the toolchain and generate the code.

STM32CubeMX Project Manager tab with a project name and the STM32CubeIDE toolchain selected

STM32 USB CDC Clock Configuration

Enable the external crystal (HSE, 8 MHz on this board) and run the system clock at 180 MHz through the PLL. The USB peripheral needs exactly 48 MHz, so check the USB clock in the clock tree after you set the PLL.

At a system clock of 180 MHz the main PLL runs its VCO at 360 MHz, and 360 divided by 48 is 7.5, so the main PLL output cannot produce 48 MHz. On the STM32F446 the 48 MHz clock multiplexer can therefore be switched to the PLLSAI P output, and CubeMX will then solve for the dividers. On other devices the main PLL Q output is used, and a system clock of 168 MHz, for example, gives exactly 48 MHz with a Q divider of 7. Always confirm that the USB clock in CubeMX reads 48 MHz.

STM32CubeMX clock tree with a 180 MHz system clock and a 48 MHz clock for the USB peripheral

STM32 USB CDC Transmit Data

The generated project contains a USB_DEVICE folder, and the file usbd_cdc_if.c in it handles CDC communication. The function CDC_Transmit_FS is not static, so it can be called from main.c after including its header.

#include "usbd_cdc_if.h"
int main ()
{
 .....
  while (1)
  {
    CDC_Transmit_FS((uint8_t *)"Hello World\n", 12);
    HAL_Delay(1000);
  }
}

The cast to uint8_t * is needed because the function expects a byte pointer.

The serial terminal prints the message once per second. The baud rate chosen in the terminal does not make any difference.

Serial terminal showing Hello World received every second over the STM32 USB CDC virtual COM port

STM32 USB CDC Receive Data

The receive function CDC_Receive_FS is static and runs automatically each time the host sends a packet, so it cannot be called from main.c. The data and its length are therefore passed to main.c through global variables. Each call delivers at most one USB packet, which is up to 64 bytes at Full Speed.

In usbd_cdc_if.c, add the variables in the PRIVATE_VARIABLES user section.

/* USER CODE BEGIN PRIVATE_VARIABLES */
uint8_t  recvDone = 0;     
uint32_t recvLen  = 0;     
uint8_t  recvBuf[64];
/* USER CODE END PRIVATE_VARIABLES */

Then edit CDC_Receive_FS inside its USER CODE 6 section, so that CubeMX keeps the change when the code is regenerated. The packet is copied before the receive buffer is released for the next packet.

static int8_t CDC_Receive_FS(uint8_t* Buf, uint32_t *Len)
{
  /* USER CODE BEGIN 6 */
  if (*Len <= sizeof(recvBuf))
  {
    memcpy(rxBuffer, Buf, *Len);
    recvLen = *Len;
    recvDone = 1;
  }

  USBD_CDC_SetRxBuffer(&hUsbDeviceFS, &Buf[0]);
  USBD_CDC_ReceivePacket(&hUsbDeviceFS);
  return (USBD_OK);
  /* USER CODE END 6 */
}

In main.c, declare the variables as extern and check the flag in the main loop. The code trims a trailing carriage return or line feed, because many terminals append one, and it compares the exact length so that a partial text such as O does not match ON.

/* USER CODE BEGIN Includes */
#include "usbd_cdc_if.h"
/* USER CODE END Includes */

extern uint8_t  recvDone;
extern uint32_t recvLen;
extern uint8_t  recvBuf[64];

while (1)
{
  if (recvDone)
  {
    recvDone = 0;
    uint32_t len = recvLen;

    /* Remove a trailing CR or LF added by the terminal */
    while ((len > 0) && ((recvBuf[len - 1] == '\r') || (recvBuf[len - 1] == '\n')))
    {
      len--;
    }

    if ((len == 2) && (memcmp(recvBuf, "ON", 2) == 0))
    {
      HAL_GPIO_WritePin(GPIOB, GPIO_PIN_2, GPIO_PIN_SET);
      CDC_Transmit_FS((uint8_t *)"LED Turned ON\r\n", 15);
    }
    else if ((len == 3) && (memcmp(recvBuf, "OFF", 3) == 0))
    {
      HAL_GPIO_WritePin(GPIOB, GPIO_PIN_2, GPIO_PIN_RESET);
      CDC_Transmit_FS((uint8_t *)"LED Turned OFF\r\n", 16);
    }
  }
}

After the commands ON and OFF are sent from the terminal, the LED changes and the STM32 sends a confirmation message back. Depending on the board, the LED may be active low, in which case swap the SET and RESET calls.

Serial terminal showing the LED Turned ON reply after sending the ON command over USB CDC
Serial terminal showing the LED Turned OFF reply after sending the OFF command over USB CDC

STM32 USB CDC printf

On a custom board without an ST-Link serial port, USB CDC is a clean way to get printf output. The C library calls the function _write for every printf, so redirecting that function sends the text to USB. Since USB CDC transmission is asynchronous, the function retries if the USB interface is busy, waiting 1 ms between attempts. It gives up after 1 second and returns -1 if the transmission cannot be started, preventing printf() from waiting indefinitely when the USB interface is unavailable.

Once CDC_Transmit_FS() returns USBD_OK, the USB stack has accepted the transmission, but the actual transfer may still be in progress.

#include <stdio.h>
#include "usbd_cdc_if.h"

int _write(int file, char *ptr, int len)
{
    uint32_t start = HAL_GetTick();

    while (CDC_Transmit_FS((uint8_t *)ptr, (uint16_t)len) != USBD_OK)
    {
        if (HAL_GetTick() - start > 1000) return -1;
        HAL_Delay(1);
    }

    return len;
}

With this function in place, printf can be called anywhere in the project.

int testNum = 1234;

while (1)
{
  printf("Printing via printf() %d\r\n", testNum);
  HAL_Delay(1000);
}
Serial monitor printf output showing  printing every one second over STM32 USB CDC virtual COM port

STM32 USB CDC Troubleshooting

SymptomLikely causeFix
No COM port appearsCharge-only cable, or the board is not in device modeUse a data cable and select Device_Only in CubeMX
Windows reports an unknown device or a descriptor errorUSB clock is not 48 MHz, or the HSE value in CubeMX does not match the crystalCheck the 48 MHz clock in the clock tree and the crystal frequency
The port appears but nothing is printedThe terminal has not opened the port, or CDC_Transmit_FS returned USBD_BUSY or USBD_FAILOpen the port first and check the return value of CDC_Transmit_FS
Nothing is printed on a Blue Pill after flashingThe D+ pull-up stays connected, so the host does not enumerate againUnplug and replug the cable, or force re-enumeration as shown above
Extra characters appear after a messageThe size argument is larger than the textUse strlen for the length
A command such as ON is not recognizedThe terminal adds CR or LF, or the text arrives as several packetsTrim the line ending and compare the exact length
printf stops the programThe code waits for a host that is not readingUse a timeout in _write as shown above
No device node on LinuxThe user has no permission for the portThe port is usually /dev/ttyACM0, so add your user to the dialout group
USB does not work on a Nucleo-64The USB connector belongs to the ST-LinkUse a board with a free USB connector, or use a UART

Conclusion

In this tutorial you configured the USB OTG FS peripheral in CDC mode, sent data to a PC, controlled an LED with commands from a serial terminal and redirected printf to USB, all through a single cable and without a bridge chip. The reconnect behavior after flashing depends on the board, so a Blue Pill needs to be unplugged unless you force re-enumeration in software.

In the next tutorial, the same USB peripheral is configured as an HID gamepad that Windows recognizes without a driver. The CDC class can also be combined with HID on one connector, as shown in the composite class tutorial.


Download Project Here

Download the CubeMX project files and HAL source code — all tested on real hardware.

If you find this useful, you can support us with a Donation as well.

Browse More STM32 USB Tutorials

About the Author
Arun Rawat
Arun Rawat
Embedded Systems Engineer · Founder, ControllersTech

Arun is an embedded systems engineer with 10+ years of experience in STM32, ESP32, and AVR microcontrollers. He created ControllersTech to share practical tutorials on embedded software, HAL drivers, RTOS, and hardware design — grounded in real industrial automation experience.

Subscribe
Notify of

2 Comments
Newest
Oldest Most Voted
Andrew Neil
1 day ago

Here:

static int8_t CDC_Receive_FS(uint8_t* Buf, uint32_t *Len)
{
  /* USER CODE BEGIN 6 */
  if (*Len <= sizeof(recvBuf))
  {
    memcpy(rxBuffer, Buf, *Len);
    recvLen = *Len;
    recvDone = 1;
  }

I think ‘rxBuffer’ should be ‘recvBuf’ ?

Rather than declare ‘recvDone’ as uint8_t, it would be better to make it a bool.

Also, rather than put the externs in main.c, they’d be better in usbd_cdc_if.h

Andrew Neil
Reply to  Andrew Neil
1 day ago

Even with that correction, it’s still assuming that the “ON” or “OFF” message will arrive in a single USB packet – it still won’t work if the characters arrive separately.

×

Don’t Miss Future STM32 Tutorials

Join thousands of developers getting free guides, code examples, and updates.