你的浏览器版本过低,可能导致网站不能正常访问!
为了你能正常使用网站功能,请使用这些浏览器。

虚拟串口控制台

[复制链接]
LC2047a 提问时间:2018-11-22 16:41 /
我想要一个虚拟串口与STM32通信。
在其中,我需要从串口获取输入命令,然后实现命令想要做的事情。

我在网上看到很多关于它的例子。 然而,它们都在“CDC_Receive_FS”中获得消息并立即重新发送到PC。 这意味着消息没有出去。 例如,离开“usbd_cdc_if.c”并在“main.c”中发送给PC。

如何在“CDC_Receive_FS”外部收到消息?

如何避免丢失消息?

usbd_cdc_if.c
  1. <font face="Tahoma">/**
  2.   * @brief  Data received over USB OUT endpoint are sent over CDC interface
  3.   *         through this function.
  4.   *
  5.   *         @note
  6.   *         This function will block any OUT packet reception on USB endpoint
  7.   *         untill exiting this function. If you exit this function before transfer
  8.   *         is complete on CDC interface (ie. using DMA controller) it will result
  9.   *         in receiving more data while previous ones are still not sent.
  10.   *
  11.   * @param  Buf: Buffer of data to be received
  12.   * @param  Len: Number of data received (in bytes)
  13.   * @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
  14.   */
  15. static int8_t CDC_Receive_FS(uint8_t* Buf, uint32_t *Len)
  16. {
  17.   /* USER CODE BEGIN 6 */
  18.   USBD_CDC_SetRxBuffer(&hUsbDeviceFS, &Buf[0]);
  19.   USBD_CDC_ReceivePacket(&hUsbDeviceFS);

  20. <font color="#ff0000">  USBD_CDC_SetTxBuffer(&hUsbDeviceFS, Buf, Len);
  21.   USBD_CDC_TransmitPacket(&hUsbDeviceFS);</font>
  22.   
  23.   return (USBD_OK);
  24.   /* USER CODE END 6 */
  25. }</font>
复制代码


如何在main.c中使用“UserRxBufferFS”和“UserTxBufferFS”?
  1. /** @defgroup USBD_CDC_IF_Private_Variables USBD_CDC_IF_Private_Variables
  2.   * @brief Private variables.
  3.   * @{
  4.   */
  5. /* Create buffer for reception and transmission           */
  6. /* It's up to user to redefine and/or remove those define */
  7. /** Received data over USB are stored in this buffer      */
  8. <font color="#ff0000">uint8_t UserRxBufferFS[APP_RX_DATA_SIZE];</font>

  9. /** Data to send over USB CDC are stored in this buffer   */
  10. <font color="#ff0000">uint8_t UserTxBufferFS[APP_TX_DATA_SIZE];</font>
复制代码



收藏 1 评论2 发布时间:2018-11-22 16:41

举报

2个回答
LC2047a 回答时间:2018-11-23 08:42:47
我正在使用Blue Pill板。

我在下面找到了例子。它教我成功在外面使用“UserRxBufferFS”和“* Len”。

  1. /**
  2.   ******************************************************************************
  3.   * @file           : main.c
  4.   * @brief          : Main program body
  5.   ******************************************************************************
  6.   * This notice applies to any and all portions of this file
  7.   * that are not between comment pairs USER CODE BEGIN and
  8.   * USER CODE END. Other portions of this file, whether
  9.   * inserted by the user or by software development tools
  10.   * are owned by their respective copyright owners.
  11.   *
  12.   * Copyright (c) 2018 STMicroelectronics International N.V.
  13.   * All rights reserved.
  14.   *
  15.   * Redistribution and use in source and binary forms, with or without
  16.   * modification, are permitted, provided that the following conditions are met:
  17.   *
  18.   * 1. Redistribution of source code must retain the above copyright notice,
  19.   *    this list of conditions and the following disclaimer.
  20.   * 2. Redistributions in binary form must reproduce the above copyright notice,
  21.   *    this list of conditions and the following disclaimer in the documentation
  22.   *    and/or other materials provided with the distribution.
  23.   * 3. Neither the name of STMicroelectronics nor the names of other
  24.   *    contributors to this software may be used to endorse or promote products
  25.   *    derived from this software without specific written permission.
  26.   * 4. This software, including modifications and/or derivative works of this
  27.   *    software, must execute solely and exclusively on microcontroller or
  28.   *    microprocessor devices manufactured by or for STMicroelectronics.
  29.   * 5. Redistribution and use of this software other than as permitted under
  30.   *    this license is void and will automatically terminate your rights under
  31.   *    this license.
  32.   *
  33.   * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS"
  34.   * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT
  35.   * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  36.   * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY
  37.   * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT
  38.   * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  39.   * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  40.   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  41.   * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  42.   * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  43.   * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  44.   * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  45.   *
  46.   ******************************************************************************
  47.   */
  48. /* Includes ------------------------------------------------------------------*/
  49. #include "main.h"
  50. #include "stm32f1xx_hal.h"
  51. #include "usart.h"
  52. #include "usb_device.h"
  53. #include "gpio.h"

  54. /* USER CODE BEGIN Includes */

  55. #include "usb_device.h"
  56. #include "usbd_core.h"
  57. #include "usbd_desc.h"
  58. #include "usbd_cdc.h"
  59. #include "usbd_cdc_if.h"
  60. /* USER CODE END Includes */

  61. /* Private variables ---------------------------------------------------------*/

  62. /* USER CODE BEGIN PV */
  63. /* Private variables ---------------------------------------------------------*/
  64. // http://www.smilefrog.net/?p=763  "USB-CDC (VCP)“
  65. extern uint8_t UserRxBufferFS[];  // declare receive data external variable
  66. extern uint8_t DataLen;  // declare receive buffer external variable
  67. /* USER CODE END PV */

  68. /* Private function prototypes -----------------------------------------------*/
  69. void SystemClock_Config(void);

  70. /* USER CODE BEGIN PFP */
  71. /* Private function prototypes -----------------------------------------------*/

  72. /* USER CODE END PFP */

  73. /* USER CODE BEGIN 0 */

  74. /* USER CODE END 0 */

  75. /**
  76.   * @brief  The application entry point.
  77.   *
  78.   * @retval None
  79.   */
  80. int main(void)
  81. {
  82.   /* USER CODE BEGIN 1 */

  83.   /* USER CODE END 1 */

  84.   /* MCU Configuration----------------------------------------------------------*/

  85.   /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  86.   HAL_Init();

  87.   /* USER CODE BEGIN Init */

  88.   /* USER CODE END Init */

  89.   /* Configure the system clock */
  90.   SystemClock_Config();

  91.   /* USER CODE BEGIN SysInit */

  92.   /* USER CODE END SysInit */

  93.   /* Initialize all configured peripherals */
  94.   MX_GPIO_Init();
  95.   MX_USART1_UART_Init();
  96.   MX_USB_DEVICE_Init();
  97.   /* USER CODE BEGIN 2 */

  98.   /* USER CODE END 2 */

  99.   /* Infinite loop */
  100.   /* USER CODE BEGIN WHILE */
  101.   while (1)
  102.   {

  103.   /* USER CODE END WHILE */

  104.   /* USER CODE BEGIN 3 */
  105.           /* to ensure the code is running */
  106.           //HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_12);
  107.           //HAL_Delay(1000);

  108.           if(DataLen > 0)
  109.           {
  110.                   while(CDC_Transmit_FS(UserRxBufferFS, DataLen));
  111.                   DataLen = 0;  
  112.           }
  113.   }
  114.   /* USER CODE END 3 */

  115. }

  116. /**
  117.   * @brief System Clock Configuration
  118.   * @retval None
  119.   */
  120. void SystemClock_Config(void)
  121. {

  122.   RCC_OscInitTypeDef RCC_OscInitStruct;
  123.   RCC_ClkInitTypeDef RCC_ClkInitStruct;
  124.   RCC_PeriphCLKInitTypeDef PeriphClkInit;

  125.     /**Initializes the CPU, AHB and APB busses clocks
  126.     */
  127.   RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  128.   RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  129.   RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  130.   RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  131.   RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  132.   RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  133.   RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  134.   if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  135.   {
  136.     _Error_Handler(__FILE__, __LINE__);
  137.   }

  138.     /**Initializes the CPU, AHB and APB busses clocks
  139.     */
  140.   RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
  141.                               |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  142.   RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  143.   RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  144.   RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  145.   RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  146.   if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  147.   {
  148.     _Error_Handler(__FILE__, __LINE__);
  149.   }

  150.   PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USB;
  151.   PeriphClkInit.UsbClockSelection = RCC_USBCLKSOURCE_PLL_DIV1_5;
  152.   if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  153.   {
  154.     _Error_Handler(__FILE__, __LINE__);
  155.   }

  156.     /**Configure the Systick interrupt time
  157.     */
  158.   HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);

  159.     /**Configure the Systick
  160.     */
  161.   HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);

  162.   /* SysTick_IRQn interrupt configuration */
  163.   HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
  164. }

  165. /* USER CODE BEGIN 4 */

  166. /* USER CODE END 4 */

  167. /**
  168.   * @brief  This function is executed in case of error occurrence.
  169.   * @param  file: The file name as string.
  170.   * @param  line: The line in file as a number.
  171.   * @retval None
  172.   */
  173. void _Error_Handler(char *file, int line)
  174. {
  175.   /* USER CODE BEGIN Error_Handler_Debug */
  176.   /* User can add his own implementation to report the HAL error return state */
  177.   while(1)
  178.   {
  179.   }
  180.   /* USER CODE END Error_Handler_Debug */
  181. }

  182. #ifdef  USE_FULL_ASSERT
  183. /**
  184.   * @brief  Reports the name of the source file and the source line number
  185.   *         where the assert_param error has occurred.
  186.   * @param  file: pointer to the source file name
  187.   * @param  line: assert_param error line source number
  188.   * @retval None
  189.   */
  190. void assert_failed(uint8_t* file, uint32_t line)
  191. {
  192.   /* USER CODE BEGIN 6 */
  193.   /* User can add his own implementation to report the file name and line number,
  194.      tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  195.   /* USER CODE END 6 */
  196. }
  197. #endif /* USE_FULL_ASSERT */

  198. /**
  199.   * @}
  200.   */

  201. /**
  202.   * @}
  203.   */

  204. /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
复制代码
  1. /**
  2.   ******************************************************************************
  3.   * @file           : usbd_cdc_if.c///
  4.   * @version        : v2.0_Cube
  5.   * @brief          : Usb device for Virtual Com Port.
  6.   ******************************************************************************
  7.   * This notice applies to any and all portions of this file
  8.   * that are not between comment pairs USER CODE BEGIN and
  9.   * USER CODE END. Other portions of this file, whether
  10.   * inserted by the user or by software development tools
  11.   * are owned by their respective copyright owners.
  12.   *
  13.   * Copyright (c) 2018 STMicroelectronics International N.V.
  14.   * All rights reserved.
  15.   *
  16.   * Redistribution and use in source and binary forms, with or without
  17.   * modification, are permitted, provided that the following conditions are met:
  18.   *
  19.   * 1. Redistribution of source code must retain the above copyright notice,
  20.   *    this list of conditions and the following disclaimer.
  21.   * 2. Redistributions in binary form must reproduce the above copyright notice,
  22.   *    this list of conditions and the following disclaimer in the documentation
  23.   *    and/or other materials provided with the distribution.
  24.   * 3. Neither the name of STMicroelectronics nor the names of other
  25.   *    contributors to this software may be used to endorse or promote products
  26.   *    derived from this software without specific written permission.
  27.   * 4. This software, including modifications and/or derivative works of this
  28.   *    software, must execute solely and exclusively on microcontroller or
  29.   *    microprocessor devices manufactured by or for STMicroelectronics.
  30.   * 5. Redistribution and use of this software other than as permitted under
  31.   *    this license is void and will automatically terminate your rights under
  32.   *    this license.
  33.   *
  34.   * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS"
  35.   * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT
  36.   * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  37.   * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY
  38.   * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT
  39.   * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  40.   * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  41.   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  42.   * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  43.   * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  44.   * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  45.   * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  46.   *
  47.   ******************************************************************************
  48.   */

  49. /* Includes ------------------------------------------------------------------*/
  50. #include "usbd_cdc_if.h"

  51. /* USER CODE BEGIN INCLUDE */

  52. /* USER CODE END INCLUDE */

  53. /* Private typedef -----------------------------------------------------------*/
  54. /* Private define ------------------------------------------------------------*/
  55. /* Private macro -------------------------------------------------------------*/

  56. /* USER CODE BEGIN PV */
  57. /* Private variables ---------------------------------------------------------*/

  58. /* USER CODE END PV */

  59. /** @addtogroup STM32_USB_OTG_DEVICE_LIBRARY
  60.   * @brief Usb device library.
  61.   * @{
  62.   */

  63. /** @addtogroup USBD_CDC_IF
  64.   * @{
  65.   */

  66. /** @defgroup USBD_CDC_IF_Private_TypesDefinitions USBD_CDC_IF_Private_TypesDefinitions
  67.   * @brief Private types.
  68.   * @{
  69.   */

  70. /* USER CODE BEGIN PRIVATE_TYPES */

  71. /* USER CODE END PRIVATE_TYPES */

  72. /**
  73.   * @}
  74.   */

  75. /** @defgroup USBD_CDC_IF_Private_Defines USBD_CDC_IF_Private_Defines
  76.   * @brief Private defines.
  77.   * @{
  78.   */

  79. /* USER CODE BEGIN PRIVATE_DEFINES */
  80. /* Define size for the receive and transmit buffer over CDC */
  81. /* It's up to user to redefine and/or remove those define */
  82. #define APP_RX_DATA_SIZE  64
  83. #define APP_TX_DATA_SIZE  64
  84. /* USER CODE END PRIVATE_DEFINES */

  85. /**
  86.   * @}
  87.   */

  88. /** @defgroup USBD_CDC_IF_Private_Macros USBD_CDC_IF_Private_Macros
  89.   * @brief Private macros.
  90.   * @{
  91.   */

  92. /* USER CODE BEGIN PRIVATE_MACRO */

  93. /* USER CODE END PRIVATE_MACRO */

  94. /**
  95.   * @}
  96.   */

  97. /** @defgroup USBD_CDC_IF_Private_Variables USBD_CDC_IF_Private_Variables
  98.   * @brief Private variables.
  99.   * @{
  100.   */
  101. /* Create buffer for reception and transmission           */
  102. /* It's up to user to redefine and/or remove those define */
  103. /** Received data over USB are stored in this buffer      */
  104. uint8_t UserRxBufferFS[APP_RX_DATA_SIZE];

  105. /** Data to send over USB CDC are stored in this buffer   */
  106. uint8_t UserTxBufferFS[APP_TX_DATA_SIZE];

  107. /* USER CODE BEGIN PRIVATE_VARIABLES */
  108. // http://www.smilefrog.net/?p=763  "USB-CDC (VCP)“
  109. uint8_t DataLen; // define receive buffer length variable
  110. /* USER CODE END PRIVATE_VARIABLES */

  111. /**
  112.   * @}
  113.   */

  114. /** @defgroup USBD_CDC_IF_Exported_Variables USBD_CDC_IF_Exported_Variables
  115.   * @brief Public variables.
  116.   * @{
  117.   */

  118. extern USBD_HandleTypeDef hUsbDeviceFS;

  119. /* USER CODE BEGIN EXPORTED_VARIABLES */

  120. /* USER CODE END EXPORTED_VARIABLES */

  121. /**
  122.   * @}
  123.   */

  124. /** @defgroup USBD_CDC_IF_Private_FunctionPrototypes USBD_CDC_IF_Private_FunctionPrototypes
  125.   * @brief Private functions declaration.
  126.   * @{
  127.   */

  128. static int8_t CDC_Init_FS(void);
  129. static int8_t CDC_DeInit_FS(void);
  130. static int8_t CDC_Control_FS(uint8_t cmd, uint8_t* pbuf, uint16_t length);
  131. static int8_t CDC_Receive_FS(uint8_t* pbuf, uint32_t *Len);

  132. /* USER CODE BEGIN PRIVATE_FUNCTIONS_DECLARATION */

  133. /* USER CODE END PRIVATE_FUNCTIONS_DECLARATION */

  134. /**
  135.   * @}
  136.   */

  137. USBD_CDC_ItfTypeDef USBD_Interface_fops_FS =
  138. {
  139.   CDC_Init_FS,
  140.   CDC_DeInit_FS,
  141.   CDC_Control_FS,
  142.   CDC_Receive_FS
  143. };

  144. /* Private functions ---------------------------------------------------------*/
  145. /**
  146.   * @brief  Initializes the CDC media low layer over the FS USB IP
  147.   * @retval USBD_OK if all operations are OK else USBD_FAIL
  148.   */
  149. static int8_t CDC_Init_FS(void)
  150. {
  151.   /* USER CODE BEGIN 3 */
  152.   /* Set Application Buffers */
  153.   USBD_CDC_SetTxBuffer(&hUsbDeviceFS, UserTxBufferFS, 0);
  154.   USBD_CDC_SetRxBuffer(&hUsbDeviceFS, UserRxBufferFS);
  155.   return (USBD_OK);
  156.   /* USER CODE END 3 */
  157. }

  158. /**
  159.   * @brief  DeInitializes the CDC media low layer
  160.   * @retval USBD_OK if all operations are OK else USBD_FAIL
  161.   */
  162. static int8_t CDC_DeInit_FS(void)
  163. {
  164.   /* USER CODE BEGIN 4 */
  165.   return (USBD_OK);
  166.   /* USER CODE END 4 */
  167. }

  168. /**
  169.   * @brief  Manage the CDC class requests
  170.   * @param  cmd: Command code
  171.   * @param  pbuf: Buffer containing command data (request parameters)
  172.   * @param  length: Number of data to be sent (in bytes)
  173.   * @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
  174.   */
  175. static int8_t CDC_Control_FS(uint8_t cmd, uint8_t* pbuf, uint16_t length)
  176. {
  177.   /* USER CODE BEGIN 5 */
  178.   switch(cmd)
  179.   {
  180.     case CDC_SEND_ENCAPSULATED_COMMAND:

  181.     break;

  182.     case CDC_GET_ENCAPSULATED_RESPONSE:

  183.     break;

  184.     case CDC_SET_COMM_FEATURE:

  185.     break;

  186.     case CDC_GET_COMM_FEATURE:

  187.     break;

  188.     case CDC_CLEAR_COMM_FEATURE:

  189.     break;

  190.   /*******************************************************************************/
  191.   /* Line Coding Structure                                                       */
  192.   /*-----------------------------------------------------------------------------*/
  193.   /* Offset | Field       | Size | Value  | Description                          */
  194.   /* 0      | dwDTERate   |   4  | Number |Data terminal rate, in bits per second*/
  195.   /* 4      | bCharFormat |   1  | Number | Stop bits                            */
  196.   /*                                        0 - 1 Stop bit                       */
  197.   /*                                        1 - 1.5 Stop bits                    */
  198.   /*                                        2 - 2 Stop bits                      */
  199.   /* 5      | bParityType |  1   | Number | Parity                               */
  200.   /*                                        0 - None                             */
  201.   /*                                        1 - Odd                              */
  202.   /*                                        2 - Even                             */
  203.   /*                                        3 - Mark                             */
  204.   /*                                        4 - Space                            */
  205.   /* 6      | bDataBits  |   1   | Number Data bits (5, 6, 7, 8 or 16).          */
  206.   /*******************************************************************************/
  207.     case CDC_SET_LINE_CODING:

  208.     break;

  209.     case CDC_GET_LINE_CODING:

  210.     break;

  211.     case CDC_SET_CONTROL_LINE_STATE:

  212.     break;

  213.     case CDC_SEND_BREAK:

  214.     break;

  215.   default:
  216.     break;
  217.   }

  218.   return (USBD_OK);
  219.   /* USER CODE END 5 */
  220. }

  221. /**
  222.   * @brief  Data received over USB OUT endpoint are sent over CDC interface
  223.   *         through this function.
  224.   *
  225.   *         @note
  226.   *         This function will block any OUT packet reception on USB endpoint
  227.   *         untill exiting this function. If you exit this function before transfer
  228.   *         is complete on CDC interface (ie. using DMA controller) it will result
  229.   *         in receiving more data while previous ones are still not sent.
  230.   *
  231.   * @param  Buf: Buffer of data to be received
  232.   * @param  Len: Number of data received (in bytes)
  233.   * @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
  234.   */
  235. static int8_t CDC_Receive_FS(uint8_t* Buf, uint32_t *Len)
  236. {
  237.   /* USER CODE BEGIN 6 */
  238.   USBD_CDC_SetRxBuffer(&hUsbDeviceFS, &Buf[0]);
  239.   USBD_CDC_ReceivePacket(&hUsbDeviceFS);

  240.   DataLen = *Len; //assign receive buffer length, don't edit any other!!!

  241.   return (USBD_OK);
  242.   /* USER CODE END 6 */
  243. }

  244. /**
  245.   * @brief  CDC_Transmit_FS
  246.   *         Data to send over USB IN endpoint are sent over CDC interface
  247.   *         through this function.
  248.   *         @note
  249.   *
  250.   *
  251.   * @param  Buf: Buffer of data to be sent
  252.   * @param  Len: Number of data to be sent (in bytes)
  253.   * @retval USBD_OK if all operations are OK else USBD_FAIL or USBD_BUSY
  254.   */
  255. uint8_t CDC_Transmit_FS(uint8_t* Buf, uint16_t Len)
  256. {
  257.   uint8_t result = USBD_OK;
  258.   /* USER CODE BEGIN 7 */
  259.   USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef*)hUsbDeviceFS.pClassData;
  260.   if (hcdc->TxState != 0){
  261.     return USBD_BUSY;
  262.   }
  263.   USBD_CDC_SetTxBuffer(&hUsbDeviceFS, Buf, Len);
  264.   result = USBD_CDC_TransmitPacket(&hUsbDeviceFS);
  265.   /* USER CODE END 7 */
  266.   return result;
  267. }

  268. /* USER CODE BEGIN PRIVATE_FUNCTIONS_IMPLEMENTATION */

  269. /* USER CODE END PRIVATE_FUNCTIONS_IMPLEMENTATION */

  270. /**
  271.   * @}
  272.   */

  273. /**
  274.   * @}
  275.   */

  276. /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
复制代码

问题1。
为什么使用“while(CDC_Transmit_FS(UserRxBufferFS,DataLen));”?
我尝试只使用“CDC_Transmit_FS(UserRxBufferFS,DataLen)”,它似乎也有用。
它与下一步“DataLen = 0”(重置DataLen)有关吗?

问题2。
只有当我在主循环中添加一些延迟(以模拟另一个任务)时,它会丢失消息或只是回转最后一个字。
如何避免丢失?

请指教!


bjflsk 回答时间:2018-11-28 12:14:26
CDC_Transmit_FS(UserRxBufferFS,DataLen);一次不一定能够发送成功。因为你发送的时候USB可能处于BUSY等状态。
所以采用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

评分

参与人数 1ST金币 +5 蝴蝶豆 +3 收起 理由
STMCU + 5 + 3

查看全部评分

所属标签

相似问题

关于意法半导体
我们是谁
投资者关系
意法半导体可持续发展举措
创新与技术
招聘信息
联系我们
联系ST分支机构
寻找销售人员和分销渠道
社区
媒体中心
活动与培训
隐私策略
隐私策略
Cookies管理
行使您的权利
关注我们
st-img 微信公众号
st-img 手机版