串口实现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

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值