CDC

COM port emulation with USB

It is possible to emulate a COM port with the USB OTG micro-AB connector.

usb

The USB communications device class (or USB CDC) is a composite Universal Serial Bus device class that is available in the STM32 Cube F4 HAL layer.

 

To test it, this example implements:

  • LED 5 is flashing with a period of 2 seconds (1 sec. on, 1 sec. off)
  • LED 4 represents the status of the user button (push or not)
  • USB OTG emulates a new COM port and echo all incoming characters

You can download the source code here or in my GitHub repository

To compile this source code in em::Blocks, you need to:

  1. Download the source files and unzip
  2. Open the project file “Usb-HAL.ebp”
  3. Check the constant definition USE_USB_FS is defined at the project level.

To do this check, right click on the project in the “management “windows, then select the “build Option…” option in the contextual menu.

USB_Constant

Click on the “Usb-Hal” in the left part of the dialog box to select the project global setting.

In the “#defines” tab of the compiler settings, check that USE_USB_FS is present.

 

Warning: There is a bug in the STM32 Cube F4 distribution files (corrected here)

In the usbd_cdc.c file, in the USBD_CDC_TransmitPacket() function, the update of the state is done after the call of transmit (that is using interrupts and also update the status).

USBD_LL_Transmit(...);
hcdc->TxState = 1;

So in case of small transmission (1 byte for example), the Transmit function can end before the function update the state with a wrong information. The solution: invert the two lines to indicate the Transmit before sending bytes.

hcdc->TxState = 1;
USBD_LL_Transmit(...);