cancel
Showing results for 
Search instead for 
Did you mean: 

How to Set USB CDC Line Coding?

Lubos KOUDELKA
ST Employee

How to Set USB CDC Line Coding?

1. What is Line coding?

Line coding is used to transfer parameters of UART interface, which is emulated using USB CDC - Virtual COM port. In STM32 legacy USB library is line coding handled in file usbd_cdc_if.c, function CDC_Control_xS(FS for Full Speed USB, HS for High Speed USB). STM32CubeMX generates CDC_Control_xS function empty, you can find handling proposal in STM32CubeMX project repository.
 

2. Line coding structure

First you need to define line coding structure:
USBD_CDC_LineCodingTypeDef LineCoding = {
  115200,                       /* baud rate */
  0x00,                         /* stop bits-1 */
  0x00,                         /* parity - none */
  0x08                          /* nb. of bits 8 */
};
then structure need to be correctly added into CDC_control_xS function:
static int8_t CDC_Control_xS(uint8_t cmd, uint8_t* pbuf, uint16_t length)
{
  /* USER CODE BEGIN 5 */
  switch(cmd)
  {
...
    case CDC_SET_LINE_CODING:
        LineCoding.bitrate = (uint32_t) (pbuf[0] | (pbuf[1] << 8) |
                                         (pbuf[2] << 16) | (pbuf[3] << 24));
        LineCoding.format = pbuf[4];
        LineCoding.paritytype = pbuf[5];
        LineCoding.datatype = pbuf[6];
        break;

      case CDC_GET_LINE_CODING:
        pbuf[0] = (uint8_t) (LineCoding.bitrate);
        pbuf[1] = (uint8_t) (LineCoding.bitrate >> 8);
        pbuf[2] = (uint8_t) (LineCoding.bitrate >> 16);
        pbuf[3] = (uint8_t) (LineCoding.bitrate >> 24);
        pbuf[4] = LineCoding.format;
        pbuf[5] = LineCoding.paritytype;
        pbuf[6] = LineCoding.datatype;
        break;
...
  return (USBD_OK);
  /* USER CODE END 5 */
}

 
Comments
MKDas
Associate II

But how to use it for USB Host? Any example plz?

Lubos KOUDELKA
ST Employee

Hello,

line coding may be used on USB host side as well to set correctly parameters of UART peripheral behind. Example of line coding handling on host side can be found in USB CDC host examples in our repositories. Multiple such examples on multiple STM32 families available, one of them on following link:

https://github.com/STMicroelectronics/STM32CubeH7/blob/master/Projects/STM32H743I-EVAL/Applications/USB_Host/CDC_Standalone/Src/cdc_configuration.c

Best regards,

Lubos

Version history
Last update:
‎2021-05-18 06:46 AM
Updated by: