STM32F103RCT6的HAL库串口2接收
时间: 2023-11-06 14:06:45 浏览: 92
1. 首先在CubeMX中配置串口2的时钟和GPIO引脚。
2. 在main.c中添加以下代码初始化串口2:
```
/* USART2 init function */
static void MX_USART2_UART_Init(void)
{
huart2.Instance = USART2;
huart2.Init.BaudRate = 115200;
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();
}
}
```
3. 在main函数中调用MX_USART2_UART_Init()函数进行初始化。
4. 在main函数中添加以下代码实现串口2的中断接收:
```
/* USER CODE BEGIN 4 */
uint8_t aRxBuffer[RXBUFFERSIZE];//定义接收缓冲区
uint8_t len = 0;
/* USER CODE END 4 */
/* USER CODE BEGIN USART2_IRQn 0 */
/* USER CODE END USART2_IRQn 0 */
/* USER CODE BEGIN USART2_IRQn 1 */
/* USER CODE END USART2_IRQn 1 */
void USART2_IRQHandler(void)
{
/* USER CODE BEGIN USART2_IRQn 0 */
uint32_t isrflags = READ_REG(huart2.Instance->SR);//获取中断标志
uint32_t cr1its = READ_REG(huart2.Instance->CR1);//获取中断使能
uint32_t cr3its = READ_REG(huart2.Instance->CR3);
uint32_t errorflags;
/* If no error occurs */
errorflags = (isrflags & (uint32_t)(USART_SR_PE | USART_SR_FE | USART_SR_ORE | USART_SR_NE));
if (errorflags == RESET)
{
/* UART in mode Receiver ---------------------------------------------------*/
if (((isrflags & USART_SR_RXNE) != RESET) && ((cr1its & USART_CR1_RXNEIE) != RESET))
{
/* 读取USART2接收到的数据 */
aRxBuffer[len++] = (uint8_t)(huart2.Instance->DR & (uint8_t)0xFF);
if(len == RXBUFFERSIZE)
{
len = 0;
}
}
}
/* USER CODE BEGIN USART2_IRQn 1 */
/* USER CODE END USART2_IRQn 1 */
}
```
5. 在main函数中添加以下代码实现读取接收缓冲区中的数据:
```
/* USER CODE BEGIN WHILE */
while (1)
{
if(len > 0)
{
HAL_UART_Transmit(&huart2, aRxBuffer, len, 1000);//将接收到的数据发送回去
len = 0;
}
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
```
阅读全文