我想要一个虚拟串口与STM32通信。
在其中,我需要从串口获取输入命令,然后实现命令想要做的事情。
我在网上看到很多关于它的例子。 然而,它们都在“CDC_Receive_FS”中获得消息并立即重新发送到PC。 这意味着消息没有出去。 例如,离开“usbd_cdc_if.c”并在“main.c”中发送给PC。
如何在“CDC_Receive_FS”外部收到消息?
如何避免丢失消息?
usbd_cdc_if.c
- <font face="Tahoma">/**
- * @brief Data received over USB OUT endpoint are sent over CDC interface
- * through this function.
- *
- * @note
- * This function will block any OUT packet reception on USB endpoint
- * untill exiting this function. If you exit this function before transfer
- * is complete on CDC interface (ie. using DMA controller) it will result
- * in receiving more data while previous ones are still not sent.
- *
- * @param Buf: Buffer of data to be received
- * @param Len: Number of data received (in bytes)
- * @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
- */
- 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);
- <font color="#ff0000"> USBD_CDC_SetTxBuffer(&hUsbDeviceFS, Buf, Len);
- USBD_CDC_TransmitPacket(&hUsbDeviceFS);</font>
-
- return (USBD_OK);
- /* USER CODE END 6 */
- }</font>
复制代码
如何在main.c中使用“UserRxBufferFS”和“UserTxBufferFS”?
- /** @defgroup USBD_CDC_IF_Private_Variables USBD_CDC_IF_Private_Variables
- * @brief Private variables.
- * @{
- */
- /* Create buffer for reception and transmission */
- /* It's up to user to redefine and/or remove those define */
- /** Received data over USB are stored in this buffer */
- <font color="#ff0000">uint8_t UserRxBufferFS[APP_RX_DATA_SIZE];</font>
- /** Data to send over USB CDC are stored in this buffer */
- <font color="#ff0000">uint8_t UserTxBufferFS[APP_TX_DATA_SIZE];</font>
复制代码
|
我在下面找到了例子。它教我成功在外面使用“UserRxBufferFS”和“* Len”。
问题1。
为什么使用“while(CDC_Transmit_FS(UserRxBufferFS,DataLen));”?
我尝试只使用“CDC_Transmit_FS(UserRxBufferFS,DataLen)”,它似乎也有用。
它与下一步“DataLen = 0”(重置DataLen)有关吗?
问题2。
只有当我在主循环中添加一些延迟(以模拟另一个任务)时,它会丢失消息或只是回转最后一个字。
如何避免丢失?
请指教!
所以采用while(CDC_Transmit_FS(UserRxBufferFS,DataLen));不断发送,直到发送成功。
DataLen = 0;原作者借用了这个变量来判断已接收到数据---- if(DataLen > 0)----,此处把它设置为0。但不建议这样做。这存在竞争风险。你的第2个问题有可能和这也相关。
问题2请参照管理员分享的文章:
https://www.stmcu.org.cn/module/forum/thread-613504-1-6.html
评分
查看全部评分