串口实现FIFO接受数据

基本原理:静态队列

/*
 * 串口的FIFO简单读取实现
 * 功能,实现串口的FIFO实现
 * 使用方法:
 * 版本:v1.0.0
 * 
 */
#include "sys.h"
#include "usartbuf.h"


USARType Usart_fifo_Read( Usart_RecerivePoint Rusart,uint8_t * buf,uint8_t length)
{
    if (Rusart->Count - length  < 0)//缓冲区没有足够的数据
    {
        return USARTREADOVER;//读数据越界
    }
    while (length--)
    {
        *buf = Rusart->Recerivrbuffer[Rusart->Pread];
        buf++;    
        Rusart->Count --;
        Rusart->Pread++;//读取指针自加
        if(Rusart->Pread == RECERIVRSIZE)
        {
            Rusart->Pread =0;
        }
            
    }
    return USARTOK;//数据读取成功
}

/*向缓冲区中写入length个数据*/
USARType Usart_fifo_write(Usart_RecerivePoint Rusart,uint8_t * buf,uint8_t length)//
{
    if (Rusart->Count + length  > RECERIVRSIZE)//写入的数据超过缓冲区
    {
        return USARTWRITEOVER;//写数据越界
    }
    while(length--)
    {
        Rusart->Recerivrbuffer[Rusart->Pwrite] = *buf;//赋值给缓冲区
        buf++;//缓冲区地址加一        
        Rusart->Count ++;
        Rusart->Pwrite++;//
        if(Rusart->Pwrite == RECERIVRSIZE)
        {
            Rusart->Pwrite =0;
        }
            
    }
    return USARTOK;//数据读取成功
    
}
 
/*清空缓冲区*/
void Usart_fifo_Clear(Usart_RecerivePoint Rusart)
{
    Rusart->Count = 0;
    Rusart->Pread =0;//读指针为0
    Rusart->Pwrite = 0;//写指针为0
}
#ifndef  _USARTBUF_H
#define  _USARTBUF_H
/*该参数设置接受区大小*/
#define RECERIVRSIZE  64//接受区大小
typedef struct  {
    int Pread;//读指针
    int Pwrite;//写指针
    int Count;//缓冲区计数
    uint8_t  Recerivrbuffer[RECERIVRSIZE];//接受缓冲区
}Usart_ReceriveType,*Usart_RecerivePoint;


#define USARType int 
#define USARTREADOVER -2//串口数据超出
#define USARTWRITEOVER  -3//串口写数据越界
#define USARTOK  1


USARType Usart_fifo_write(Usart_RecerivePoint Rusart,uint8_t * buf,uint8_t length);USARType Usart_fifo_Read( Usart_RecerivePoint Rusart,uint8_t * buf,uint8_t length);
void Usart_fifo_Clear(Usart_RecerivePoint Rusart);

#endif/*_USARTBUF_H*/

使用方式:定义一个Usart_ReceriveType类型的缓冲队列,然后就可以利用上述文件中提供的三个函数来实现串口的FIFO的数据接受和读取

使用的时候可以利用

USARType Usart_fifo_write(Usart_RecerivePoint Rusart,uint8_t * buf,uint8_t length);

USARType Usart_fifo_Read( Usart_RecerivePoint Rusart,uint8_t * buf,uint8_t length);

这两个函数来向缓冲区中写入和读取数据,其中参数的含义如下

第一个参数(Rusart)是串口缓冲区指针类型,用来标示串口,

第二个参数(buf)是一个指uint8_t类型的指针,用来指向要写入或者读取数据的首地址,

第三个参数(length)表示要写入或者读取的数据长度

出口参数USARType 实际是一个整形数据,返回值得意义入下

#define USARTREADOVER –2//串口数据超出

#define USARTWRITEOVER -3//串口写数据越界

#define USARTOK 1// 串口缓冲区数据读出或者写入成功

void Usart_fifo_Clear(Usart_RecerivePoint Rusart);

这个函数用来清空缓冲区数据,实现起来比较简单

原文地址:https://www.cnblogs.com/memorypro/p/6159114.html