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 line coding is handled by a function called CDC_Control_xS (FS for Full speed USB mode, HS for High speed USB mode) located in the usbd_cdc_if.c file.
STM32CubeMX generates the CDC_Control_xS function empty, you can find a handling proposal in the STM32CubeMX project repository.
2. Line coding structure
First you need to define the line coding structure:
USBD_CDC_LineCodingTypeDef LineCoding = {
115200, /* baud rate */
0x00, /* stop bits-1 */
0x00, /* parity - none */
0x08 /* nb. of bits 8 */
};
Then, the structure needs to be correctly added into the 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] << |
(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 */
}