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
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;
(args, format);
va_start= vsnprintf((char *)UserTxBufferFS, APP_TX_DATA_SIZE, (char *)format, args);
length (args);
va_end(UserTxBufferFS, length);
CDC_Transmit_FS}
add this to .h
file to export this api, include this .h
file in which .c
file 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"
("test:%f\n",0.1); labelusb_printf
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 */
*hcdc = (USBD_CDC_HandleTypeDef*)hUsbDeviceFS.pClassData;
USBD_CDC_HandleTypeDef if (hcdc->TxState != 0){
return USBD_BUSY;
}
(&hUsbDeviceFS, Buf, Len);
USBD_CDC_SetTxBuffer= USBD_CDC_TransmitPacket(&hUsbDeviceFS);
result /* USER CODE END 7 */
while(hcdc->TxState)
{
if(HAL_GetTick() - Timeout >=10)//超时
{
break;
}
}
return result;
}