基于SC32F53128标准外设库开发UART FIFO下接收不定长帧数据模式代码
时间: 2023-11-27 22:04:32 浏览: 24
好的,以下是基于SC32F53128标准外设库开发UART FIFO下接收不定长帧数据模式的代码:
```c
#include "SC32F53xx.h"
#include "sc32f53xx_uart.h"
#define BUFFER_SIZE 256
volatile uint8_t rx_buffer[BUFFER_SIZE];
volatile uint8_t rx_head = 0;
volatile uint8_t rx_tail = 0;
void UART_IRQHandler(void)
{
uint8_t ch;
if (UART_GetITStatus(SC32F53xx_UART, UART_IT_RXNE) != RESET)
{
ch = UART_ReceiveData(SC32F53xx_UART);
if (((rx_tail + 1) % BUFFER_SIZE) != rx_head)
{
rx_buffer[rx_tail] = ch;
rx_tail = (rx_tail + 1) % BUFFER_SIZE;
}
}
}
void UART_Init(void)
{
UART_InitTypeDef uart_init_struct;
NVIC_InitTypeDef nvic_init_struct;
UART_StructInit(&uart_init_struct);
uart_init_struct.UART_BaudRate = 115200;
uart_init_struct.UART_WordLength = UART_WordLength_8b;
uart_init_struct.UART_StopBits = UART_StopBits_1;
uart_init_struct.UART_Parity = UART_Parity_No;
uart_init_struct.UART_HardwareFlowControl = UART_HardwareFlowControl_None;
UART_Init(SC32F53xx_UART, &uart_init_struct);
nvic_init_struct.NVIC_IRQChannel = UART_IRQn;
nvic_init_struct.NVIC_IRQChannelPriority = 0;
nvic_init_struct.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&nvic_init_struct);
UART_ITConfig(SC32F53xx_UART, UART_IT_RXNE, ENABLE);
UART_Cmd(SC32F53xx_UART, ENABLE);
}
int main(void)
{
uint8_t ch;
uint8_t frame_length;
uint8_t i;
UART_Init();
while (1)
{
if (rx_head != rx_tail)
{
ch = rx_buffer[rx_head];
rx_head = (rx_head + 1) % BUFFER_SIZE;
if (ch == 0x7E) // 帧起始符
{
ch = rx_buffer[rx_head];
rx_head = (rx_head + 1) % BUFFER_SIZE;
if (ch == 0x00) // 协议版本号
{
ch = rx_buffer[rx_head];
rx_head = (rx_head + 1) % BUFFER_SIZE;
frame_length = ch;
ch = rx_buffer[rx_head];
rx_head = (rx_head + 1) % BUFFER_SIZE;
frame_length |= (ch << 8);
for (i = 0; i < frame_length; i++)
{
ch = rx_buffer[rx_head];
rx_head = (rx_head + 1) % BUFFER_SIZE;
// 处理接收到的数据
}
}
}
}
}
}
```
这段代码实现了一个简单的UART接收不定长帧数据的功能。当接收到数据时,会将数据存储在循环缓冲区中,然后在主函数中处理接收到的数据。具体实现中,会先判断是否接收到了帧起始符0x7E,然后再读取协议版本号和帧长度。最后根据帧长度读取数据并进行处理。
需要注意的是,这段代码中使用了循环缓冲区来存储接收到的数据,可以有效避免数据丢失的问题。另外,为了避免在中断中处理过多的数据,建议在主函数中处理数据。