STM32 UART FIFO收发例程
时间: 2023-09-14 21:09:47 浏览: 158
好的,以下是一个简单的基于STM32的UART FIFO收发例程,代码使用HAL库编写:
```c
#include "stm32f4xx_hal.h"
#define UART_BUFFER_SIZE 128
UART_HandleTypeDef huart2;
uint8_t uart_rx_buffer[UART_BUFFER_SIZE];
uint8_t uart_tx_buffer[UART_BUFFER_SIZE];
uint8_t uart_rx_data = 0;
uint8_t uart_rx_data_available = 0;
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if (huart->Instance == USART2)
{
// Check if receive buffer is full
if (uart_rx_data_available < UART_BUFFER_SIZE)
{
uart_rx_buffer[uart_rx_data_available++] = uart_rx_data;
}
else
{
uart_rx_data_available = 0;
}
// Start listening for new data
HAL_UART_Receive_IT(&huart2, &uart_rx_data, 1);
}
}
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
// Nothing to do here
}
void UART_Init()
{
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;
HAL_UART_Init(&huart2);
// Start listening for data
HAL_UART_Receive_IT(&huart2, &uart_rx_data, 1);
}
void UART_Send(const uint8_t *data, uint16_t size)
{
HAL_UART_Transmit_IT(&huart2, (uint8_t *)data, size);
}
uint8_t UART_Read()
{
if (uart_rx_data_available == 0)
{
return 0;
}
uint8_t data = uart_rx_buffer[0];
uart_rx_data_available--;
for (uint8_t i = 0; i < uart_rx_data_available; i++)
{
uart_rx_buffer[i] = uart_rx_buffer[i + 1];
}
return data;
}
void UART_ReadBuffer(uint8_t *buffer, uint16_t size)
{
if (uart_rx_data_available < size)
{
size = uart_rx_data_available;
}
for (uint16_t i = 0; i < size; i++)
{
buffer[i] = uart_rx_buffer[i];
}
uart_rx_data_available -= size;
for (uint16_t i = 0; i < uart_rx_data_available; i++)
{
uart_rx_buffer[i] = uart_rx_buffer[i + size];
}
}
int main(void)
{
HAL_Init();
UART_Init();
while (1)
{
uint8_t data = UART_Read();
if (data != 0)
{
// Handle received data
}
// Do other stuff
}
}
```
这个例程使用了UART2,可以根据需要修改。主要使用了两个缓冲区(rx_buffer和tx_buffer),分别用于接收和发送数据。数据接收使用了中断,每当有数据到达时,会调用HAL_UART_RxCpltCallback函数进行处理。数据发送也使用了中断,对于比较长的数据可以使用HAL_UART_Transmit_DMA函数实现DMA传输,更加高效。
阅读全文