stm32 usb cdc vitural serial port

stm32
Author

dd21

Published

January 6, 2023

Abstract

when we are using stm32 development, we offen used the usart, but we don’t want to add the usb2serial mode. we hope we can use the usb liner to connect with pc and stm32.

this usb cdc stolve the proublem, we can use the usart easily.

Referance

texthttps://blog.csdn.net/qq_15504787/article/details/113787699

fix usb cdc continues bug

careate project with CubeMx

config usb clock

the clock must be set to 48Mhz

open the project

open the file usbd_cdc_if.c

add the code like this

#include <stdarg.h>

void usb_printf(const char *format, ...)
{
    va_list args;
    uint32_t length;

    va_start(args, format);
    length = vsnprintf((char *)UserTxBufferFS, APP_TX_DATA_SIZE, (char *)format, args);
    va_end(args);
    CDC_Transmit_FS(UserTxBufferFS, length);
}

add this to .h file to export this api, include this .hfile in which .cfile can use the usb_printf to print something with usb. usbd_cdc_if.h

void usb_printf(const char *format, ...);

demo

#include "usbd_cdc_if.h"

labelusb_printf("test:%f\n",0.1);

error

if you can not see something output in serial assistant, you can try add the micLib

Other

if you want to send continues data with CDC_Transmit_FS like this

you will need to fix this bug, otherwise you will get same data of which one you send.

fix usb_cdc continues send bug

update the the CDC_Transmit_FS function. if you don’t want to fix you can try hal_delay()

uint8_t CDC_Transmit_FS(uint8_t* Buf, uint16_t Len)
{
  uint8_t result = USBD_OK;
    uint32_t Timeout = HAL_GetTick();
  /* USER CODE BEGIN 7 */
  USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef*)hUsbDeviceFS.pClassData;
  if (hcdc->TxState != 0){
    return USBD_BUSY;
  }
  USBD_CDC_SetTxBuffer(&hUsbDeviceFS, Buf, Len);
  result = USBD_CDC_TransmitPacket(&hUsbDeviceFS);
  /* USER CODE END 7 */
    while(hcdc->TxState)
    {
        if(HAL_GetTick() - Timeout >=10)//超时
        {
            break;
        }
    }
  return result;
}