stm32完整的串口中断接收代码
时间: 2023-09-20 13:03:39 浏览: 30
以下是一个简单的STM32串口接收中断代码示例:
```c
#include "stm32f4xx.h"
#include <string.h>
#define UART_BUFFER_SIZE 128
volatile uint8_t uart_rx_buffer[UART_BUFFER_SIZE];
volatile uint8_t uart_rx_index = 0;
void USART2_IRQHandler(void)
{
if (USART_GetITStatus(USART2, USART_IT_RXNE) != RESET)
{
uart_rx_buffer[uart_rx_index] = USART_ReceiveData(USART2);
uart_rx_index++;
if (uart_rx_index >= UART_BUFFER_SIZE)
{
uart_rx_index = 0;
}
}
}
void USART2_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
USART_InitTypeDef USART_InitStruct;
NVIC_InitTypeDef NVIC_InitStruct;
// Enable clock for GPIOA and USART2
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
// Connect PA2 and PA3 with USART2
GPIO_PinAFConfig(GPIOA, GPIO_PinSource2, GPIO_AF_USART2);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource3, GPIO_AF_USART2);
// Configure USART2 Tx and Rx pins as alternate function push-pull
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOA, &GPIO_InitStruct);
// Configure USART2
USART_StructInit(&USART_InitStruct);
USART_InitStruct.USART_BaudRate = 115200;
USART_InitStruct.USART_WordLength = USART_WordLength_8b;
USART_InitStruct.USART_StopBits = USART_StopBits_1;
USART_InitStruct.USART_Parity = USART_Parity_No;
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_Init(USART2, &USART_InitStruct);
// Enable USART2 receive interrupt
USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
// Configure NVIC for USART2 interrupt
NVIC_InitStruct.NVIC_IRQChannel = USART2_IRQn;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStruct);
// Enable USART2
USART_Cmd(USART2, ENABLE);
}
int main(void)
{
USART2_Init();
while (1)
{
if (uart_rx_index > 0)
{
// Process received data
// ...
// Clear receive buffer
memset(uart_rx_buffer, 0, UART_BUFFER_SIZE);
uart_rx_index = 0;
}
}
}
```
此示例使用了USART2和PA2/PA3引脚。在`USART2_IRQHandler`中,我们检查接收中断标志(`USART_IT_RXNE`),如果已设置,则读取接收数据寄存器(`USART_ReceiveData`)并将其存储到接收缓冲区中。在主循环中,我们检查`uart_rx_index`是否大于0,如果是,则处理接收到的数据(在这里需要自己实现),并清除接收缓冲区。