首先进行USB的配置,时钟配置USB为48Hz,usb选择device,usb_device选择VCP,最后在manager中更改heap size为0x600
先对vcp初始化
void USB_Status_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOA_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_11 | GPIO_PIN_12, GPIO_PIN_RESET);
/*Configure GPIO pin : W25Q256_CS_Pin */
GPIO_InitStruct.Pin = GPIO_PIN_11 | GPIO_PIN_12;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_PULLDOWN;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
HAL_Delay(10);
}
初始化区域写入
USB_Status_Init();
使用CDC_Transmit_FS进行发送数据
CDC_Transmit_FS(TXT, sizeof(TXT));
(TXT也为u8)
CDC_Transmit_FS函数位置为usbd_cdc_if.c
优化后
uint8_t CDC_Transmit_FS(uint8_t* Buf, uint16_t Len)
{
uint8_t result = USBD_OK;
/* USER CODE BEGIN 7 */
uint32_t TimeStart = HAL_GetTick();
USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef*)hUsbDeviceFS.pClassData;
//if (hcdc->TxState != 0) return USBD_BUSY;
while(hcdc->TxState)
{
if(HAL_GetTick()-TimeStart > 10)
return USBD_BUSY;
else
break;
}
USBD_CDC_SetTxBuffer(&hUsbDeviceFS, Buf, Len);
result = USBD_CDC_TransmitPacket(&hUsbDeviceFS);
TimeStart = HAL_GetTick();
while(hcdc->TxState)
{
if(HAL_GetTick()-TimeStart > 10)
return USBD_BUSY;
}
/* USER CODE END 7 */
return result;
}
虚拟串口接收
使用CDC_Receive_FS函数
注意:CDC_Receive_FS()是接收函数。这个函数不需要调用。直接在函数中添加代码把接受到的数据和数据长度复制到自己定义的接收缓存。
uint8_t CDC_Receive_FS(uint8_t* Buf, uint32_t *Len)
{
/* USER CODE BEGIN 6 */
p1=(Buf[0]-'0')*1000+(Buf[1]-'0')*100+(Buf[2]-'0')*10+(Buf[3]-'0');
p2=(Buf[5]-'0')*1000+(Buf[6]-'0')*100+(Buf[7]-'0')*10+(Buf[8]-'0');
//USBD_CDC_SetRxBuffer(&hUsbDeviceFS, &Buf[0]);
USBD_CDC_ReceivePacket(&hUsbDeviceFS);
//CDC_Transmit_FS(Buf, sizeof(Buf));
return (USBD_OK);
/* USER CODE END 6 */
}
此外,不同.c文件中变量互相使用,在A文件中声明p变量,在B文件中使用时用extern定义