使用STM32G431创建USB转TTL和USB转CAN功能的模块,使用了USBCDC类的复合,生成两个COM口,当CAN和串口同时使用时,不打开串口的COM口仅打开CAN的COM口有时主机接收不到上位机的消息,这是什么原因?
这是串口向主机的发送函数
uint8_t CDC_Transmit_FS(uint8_t* Buf, uint16_t Len)
{
uint8_t result = USBD_OK;
/* USER CODE BEGIN 7 */
HAL_UART_Transmit_DMA(&huart2,Buf,Len);
system_irq_disable();
// Process transmit buffer
USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef*)hUsbDeviceFS.pClassData;
if (hcdc->TxState != 0){
return USBD_BUSY;
}
USBD_CDC_SetTxBuffer(&hUsbDeviceFS, Buf, Len);
USBD_CDC_TransmitPacket(&hUsbDeviceFS, CDC2_IN_EP);
system_irq_enable();
/* USER CODE END 7 */
return USBD_OK;
}
这是CAN的发送函数
// Process transmit buffer
USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef*)hUsbDeviceFS.pClassData;
if(hcdc->TxState == 0)
{
uint16_t linbuf_ctr = 0;
while(txbuf.tail != txbuf.head)
{
tx_linbuf[linbuf_ctr++] = txbuf.data[txbuf.tail];
txbuf.tail = (txbuf.tail + 1UL) % USBTXQUEUE_LEN;
// Take up to the number of bytes to fill the linbuf
if(linbuf_ctr >= TX_LINBUF_SIZE)
break;
}
if(linbuf_ctr > 0)
{
// Set transmit buffer and start TX
USBD_CDC_SetTxBuffer(&hUsbDeviceFS, tx_linbuf, linbuf_ctr);
USBD_CDC_TransmitPacket(&hUsbDeviceFS, CDC_IN_EP);
}
}
``````