USB CDC
2026-05-29
Edited: 2026-05-29
This is basically just a faster UART, since it is bi-directional and asynchronous, but you don't need a USB-UART converter. For STM32, go to Middlewares and add USB_DEVICE and select CDC to enable this. As with most USBs, make sure it is getting 48 MHz of clock frequency. To transmit data, just do a simple
#include "usbd_cdc_if.c"
CDC_Transmit_FS(uint8_t* data, uint16_t data_len);Receiving data is bit more complex, but not too bad. You should first define your handler function somewhere, like in main.c or wherever. Then under USB_DEVICE/App/usbd_cdc_if.c, call the handler function
// In main or wherever, just be sure to export the function
void your_handler(uint8_t* data, uint16_t data_len)
{
// do stuf with the data...
// maybe call CDC_Transmit_FS(...) too
}
// Then in USB_DEVICE/App/usbd_cdc_if.c
// This function is already provided, just add your stuff to it
static int8_t CDC_Receive_FS(uint8_t* Buf, uint32_t *Len)
{
// These two lines should be there already
USBD_CDC_SetRxBuffer(&, &Buf[0]);
USBD_CDC_ReceivePacket(&);
// Call your handler, and then reset the buffer `UserRxBufferFS` for next time
your_handler(, *);
memset(, '\0', *);
return (USBD_OK);
}Note that the default RX and TX buffer for CDC is set to 2048, you can tweak it of course. You can use the USB to reroute printf to transmitting data over CDC, for a poor man's STEGGER RTT.