1,新建STM32F072项目,启用调试口,启用外部8M时钟,



2,启用USB设备,启用NVIC中断

3,Middleware→USB_DEVICE选择Communication Device

4,配置项目名称,输出地址,输出IDE类型,生成代码


5,打开项目代码,打开usb_cdc_if.c文件

这里有3个接口函数
//USB串口参数控制
static int8_t CDC_Control_FS(uint8_t cmd, uint8_t* pbuf, uint16_t length)
//USB串口数据接收回调
static int8_t CDC_Receive_FS(uint8_t* Buf, uint32_t *Len)
//USB串口数据发送
uint8_t CDC_Transmit_FS(uint8_t* Buf, uint16_t Len)
修改接收回调函数,调用发送函数CDC_Transmit_FS,让USB收到的上位机数据返回,可用USB连接电脑,通过串口助手发送数据,查看是否能够收到数据回传
static int8_t CDC_Receive_FS(uint8_t* Buf, uint32_t *Len)
{
/* USER CODE BEGIN 6 */
USBD_CDC_SetRxBuffer(&hUsbDeviceFS, &Buf[0]);
USBD_CDC_ReceivePacket(&hUsbDeviceFS);
CDC_Transmit_FS(Buf,*Len);
return (USBD_OK);
/* USER CODE END 6 */
}
6,如果需要使用物理串口,则把物理串口收到的数据通过CDC_Transmit_FS发送给上位机,虚拟串口收到的数据通过物理串口发送,需要注意CDC_Receive_FS函数是在USB中断中回调,需要防止与主循环冲突。
7, CDC_Control_FS 函数中 CDC_SET_LINE_CODING命令会传递物理串口的参数,如果不使用物理串口,则不用关心内容。
CDC_SET_LINE_CODING命令会收到7字节数据,前4字节是波特率,MSB大端格式,后3个字节分别是停止位、校验模式、数据bits宽度控制信息。
/*******************************************************************************/
/* Line Coding Structure */
/*-----------------------------------------------------------------------------*/
/* Offset | Field | Size | Value | Description */
/* 0 | dwDTERate | 4 | Number |Data terminal rate, in bits per second*/
/* 4 | bCharFormat | 1 | Number | Stop bits */
/* 0 - 1 Stop bit */
/* 1 - 1.5 Stop bits */
/* 2 - 2 Stop bits */
/* 5 | bParityType | 1 | Number | Parity */
/* 0 - None */
/* 1 - Odd */
/* 2 - Even */
/* 3 - Mark */
/* 4 - Space */
/* 6 | bDataBits | 1 | Number Data bits (5, 6, 7, 8 or 16). */
/*******************************************************************************/
近期评论