stm32串口中断接收数据完整代码
时间: 2023-08-07 19:27:10 浏览: 94
stm32串口接收任意字符的中断代码.zip
5星 · 资源好评率100%
以下是基于HAL库的STM32串口中断接收数据完整代码示例:
```c
#include "main.h"
#include <string.h>
UART_HandleTypeDef huart2;
uint8_t rx_buffer[10];
uint8_t rx_data;
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART2_UART_Init(void);
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_USART2_UART_Init();
if(HAL_UART_Receive_IT(&huart2, &rx_data, 1) != HAL_OK)
{
// 接收失败,处理错误
}
while (1)
{
}
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if(huart == &huart2)
{
if(rx_data == '\n')
{
// 处理接收到的数据
// ...
HAL_UART_Transmit(&huart2, rx_buffer, strlen(rx_buffer), 1000); // 回传接收到的数据
memset(rx_buffer, 0, sizeof(rx_buffer)); // 清空接收缓冲区
}
else
{
if(HAL_UART_Receive_IT(&huart2, &rx_data, 1) != HAL_OK)
{
// 接收失败,处理错误
}
else
{
rx_buffer[strlen(rx_buffer)] = rx_data; // 将数据存入接收缓冲区
}
}
}
}
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
{
Error_Handler();
}
}
static void MX_USART2_UART_Init(void)
{
huart2.Instance = USART2;
huart2.Init.BaudRate = 9600;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart2) != HAL_OK)
{
Error_Handler();
}
}
static void MX_GPIO_Init(void)
{
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
}
void Error_Handler(void)
{
__disable_irq();
while (1)
{
}
}
#ifdef USE_FULL_ASSERT
void assert_failed(uint8_t *file, uint32_t line)
{
}
#endif
```
在这个代码中,我们使用了USART2串口,并设置波特率为9600。当接收到的数据为换行符时,将接收到的数据回传回去,并清空接收缓冲区。如果还未接收完毕,则继续接收,并将数据存入接收缓冲区。这个代码中没有使用任何RTOS操作系统,如果需要使用RTOS,需要进行相应的修改。
阅读全文