STM32 uart 中断fifo 接收数组例程 标准库
时间: 2023-08-16 17:03:46 浏览: 170
以下是一个基于STM32标准库的UART中断接收FIFO数组例程:
```c
#include "stm32f4xx.h"
#include <string.h>
#define RX_BUFFER_SIZE 256
volatile uint8_t rx_buffer[RX_BUFFER_SIZE];
volatile uint16_t rx_index = 0;
void USART2_IRQHandler(void)
{
if(USART_GetITStatus(USART2, USART_IT_RXNE) != RESET)
{
uint8_t rx_data = USART_ReceiveData(USART2);
if(rx_index < RX_BUFFER_SIZE)
{
rx_buffer[rx_index++] = rx_data;
}
}
}
int main(void)
{
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
// Enable peripheral clocks
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
// Configure USART2 Tx (PA2) as alternate function push-pull
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource2, GPIO_AF_USART2);
// Configure USART2 Rx (PA3) as input floating
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource3, GPIO_AF_USART2);
// Configure USART2
USART_InitStructure.USART_BaudRate = 115200;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(USART2, &USART_InitStructure);
// Enable USART2 RX interrupt
USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
// Configure NVIC for USART2 interrupt
NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
// Enable USART2
USART_Cmd(USART2, ENABLE);
while(1)
{
// Check if there is any data in the buffer
if(rx_index > 0)
{
// Process the received data
uint8_t rx_data[RX_BUFFER_SIZE];
memcpy(rx_data, rx_buffer, rx_index); // Copy the data to a temporary buffer
rx_index = 0; // Reset the index
// Do something with the received data
}
}
}
```
在这个例程中,我们使用USART2作为例子,可以根据需要进行修改。代码中使用了一个256字节的接收缓冲区,当接收到一个字节时,将其放入缓冲区中,并将接收指针加一。当需要处理接收到的数据时,将缓冲区中的数据复制到一个临时数组中,并将接收指针重置为0。可以在主循环中处理接收到的数据。
阅读全文