STM32无法使用HAL_UART_Recceive_IT接收数据

时间:2019-05-10 12:14:20

标签: c stm32 uart stm32f4 nucleo

我是STM32的初学者,我有一个项目,需要从其他设备(如arduino)接收数据,现在我尝试从UART 3传输数据,并通过UART 1接收数据,但是我无法获取任何数据。我将TX uart 3连接到RX uart 1,将TX uart 1连接到RX uart 3。

/* USER CODE BEGIN PV */
int i = 0;
char bufferReceive[6], bufferTransmit[10];

/* USER CODE END PV */

/* USER CODE BEGIN 0 */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    if (huart->Instance == USART1)  //current UART
        {
        HAL_UART_Receive_IT(&huart1, (uint8_t*)bufferReceive, 1);   //activate UART receive interrupt every time
        }
}

/* USER CODE END 0 */

int main(void)
{
 HAL_UART_Receive_IT(&huart1, (uint8_t*)bufferReceive, 1);
 while (1)
  {
    /* USER CODE END WHILE */`enter code here`


     sprintf(bufferTransmit,"%d\n",i);
      HAL_UART_Transmit(&huart3, (uint8_t*)bufferTransmit, sizeof(bufferTransmit), 1000);
                    HAL_Delay(500);

                    i++;

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

2 个答案:

答案 0 :(得分:0)

第一件事,您的代码凌乱且难以阅读。

第二,在while(1)之前,您缺少整个初始化区域,因此您的系统不应执行任何操作。

/* USER CODE BEGIN PV */
int i = 0;
char bufferReceive[6], bufferTransmit[10];
/* USER CODE END PV */

/* USER CODE BEGIN 0 */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    if (huart->Instance == USART1)
    {
        HAL_UART_Receive_IT(&huart1, (uint8_t*)bufferReceive, 1);
    }
}
/* USER CODE END 0 */

int main(void)
{
    /* USER CODE BEGIN 1 */

    /* USER CODE END 1 */


    /* MCU Configuration--------------------------------------------------------*/

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

    /* USER CODE BEGIN Init */

    /* USER CODE END Init */

    /* Configure the system clock */
    SystemClock_Config();

    /* USER CODE BEGIN SysInit */

    /* USER CODE END SysInit */

    /* Initialize all configured peripherals */
    MX_GPIO_Init();
    MX_USART3_UART_Init();
    MX_USART1_UART_Init();
    /* USER CODE BEGIN 2 */
    HAL_UART_Receive_IT(&huart1, (uint8_t*)bufferReceive, 1);
    /* USER CODE END 2 */

    /* Infinite loop */
    /* USER CODE BEGIN WHILE */
    while (1)
    {
        sprintf(bufferTransmit,"%d\n",i);
        HAL_UART_Transmit(&huart3, (uint8_t*)bufferTransmit, sizeof(bufferTransmit), 1000);
        HAL_Delay(500);
        i++;
        /* USER CODE END WHILE */
        /* USER CODE BEGIN 3 */
    }
    /* USER CODE END 3 */
}

您在HAL_UART_Receive_IT(&huart1, (uint8_t*)bufferReceive, 1);处收到一个字节。

不等它就继续前进。

接下来,您发送bufferTransmit,这将导致UART1接收一个字节,并继续在同一存储位置一一接收所有字节。

似乎您没有正确使用i,因为您可能想要使用HAL_UART_Receive_IT(&huart1, (uint8_t*)&bufferReceive[i], 1);

答案 1 :(得分:0)

您不初始化任何内容。必须先设置外围设备,引脚,时钟等,然后才能工作。