Files
gd32e230_bootloader/Src/uart_ring_buffer.c

59 lines
1.7 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "uart_ring_buffer.h"
// 环形缓冲区结构体定义(精简版)
struct uart_ring_buffer {
volatile uint8_t buffer[UART_RX_BUFFER_SIZE];
volatile uint8_t head; // 写指针
volatile uint8_t tail; // 读指针
};
static uart_ring_buffer_t uart_rx_buf = {0};
static void uart_ring_buffer_reset_state(void) {
uart_rx_buf.head = 0;
uart_rx_buf.tail = 0;
}
void uart_ring_buffer_init(void) {
uart_ring_buffer_reset_state();
}
uint8_t uart_ring_buffer_available(void) {
uint8_t h = uart_rx_buf.head;
uint8_t t = uart_rx_buf.tail;
return (uint8_t)((h + UART_RX_BUFFER_SIZE - t) % UART_RX_BUFFER_SIZE);
}
/**
* @brief 从UART环形缓冲区中获取一个数据
*
* @return int 成功返回获取到的8位数据如果缓冲区为空则返回-1
*/
int uart_ring_buffer_get(void) {
// 检查环形缓冲区是否为空tail与head相等表示缓冲区为空
if (uart_rx_buf.tail == uart_rx_buf.head) return -1;
// 从缓冲区tail位置获取数据
uint8_t data = uart_rx_buf.buffer[uart_rx_buf.tail];
// 更新tail位置实现环形缓冲区的循环使用
// 使用取模运算确保tail在缓冲区大小范围内循环
uart_rx_buf.tail = (uart_rx_buf.tail + 1) % UART_RX_BUFFER_SIZE;
// 返回获取到的数据
return data;
}
bool uart_ring_buffer_put(uint8_t data) {
uint8_t next = (uart_rx_buf.head + 1) % UART_RX_BUFFER_SIZE;
if (next != uart_rx_buf.tail) {
uart_rx_buf.buffer[uart_rx_buf.head] = data;
uart_rx_buf.head = next;
return true;
} else {
// 缓冲区满,静默丢弃新数据
return false;
}
}
void uart_ring_buffer_clear(void) {
uart_ring_buffer_reset_state();
}