原创 一年没写了.今天回来看看,顺便发个缓冲环的c代码

2007-12-21 22:35 3267 8 8 分类: MCU/ 嵌入式
 



 一般在串口等驱动中经常遇到把固定缓冲区首尾相接的情况.例如232,485等这样的通信接口.写了一个针对这样条件下的缓冲环,已经测试通过.

 

大家用的好,别忘留个记号,呵呵.

 


memring.h 文件



typedef struct _memring     MEMRING;


struct _memring
{
 int head;
 int tail;
 int length;
 unsigned char *pring;
 int (*dataLengthInRing)(struct _memring* );
 int (*ringIsEmtpy)(struct _memring* );
 int (*ringIsFull)(struct _memring* );
 void(*dataPushRing)(struct _memring* ,unsigned char );
 unsigned char (*dataPopRing)(struct _memring* ); 
};


 


memring.c 文件



#include "memring.h"
#include "2410add.h"

int memDataLengthInRing(struct _memring * memring)
{
 unsigned int savereg;
 int ret;
 //disable all interrupt
 savereg=rINTMSK;
 rINTMSK=0XFFFFFFFF;
 ret=(memring->length + memring->tail-memring->head ) % memring->length;
 //recover
 rINTMSK=savereg;
 return ret;
}

int memRingIsEmpty(struct _memring * memring)
{
 unsigned int savereg;
 int ret;
 //disable all interrupt
 savereg=rINTMSK;
 rINTMSK=0XFFFFFFFF;
 ret=(memring->head == memring->tail);
 //recover
 rINTMSK=savereg;
 return ret;
}


 


int memRingIsFull(struct _memring * memring)
{
 unsigned int savereg;
 int ret;
 //disable all interrupt
 savereg=rINTMSK;
 rINTMSK=0XFFFFFFFF;


 ret=( ((memring->tail+1) % memring->length ) == memring->head);


 //recover
 rINTMSK=savereg;
 return ret;
}


void memDataPushRing(struct _memring * memring,unsigned char ch)
{
 unsigned int savereg;


 //disable all interrupt
 savereg=rINTMSK;
 rINTMSK=0XFFFFFFFF;


 memring->pring[memring->tail] = (ch); 
 memring->tail = ( memring->tail + 1 ) % memring->length; 


 //recover
 rINTMSK=savereg;
}


unsigned char memDataPopRing(struct _memring * memring)
{
 unsigned int savereg;
 unsigned char ch;
 //disable all interrupt
 savereg=rINTMSK;
 rINTMSK=0XFFFFFFFF;


 ch = memring->pring[memring->head]; 
 memring->head = ( memring->head + 1 ) % memring->length;
 //recover
 rINTMSK=savereg;
 return ch;
}


void memringCreat(struct _memring * memring,unsigned char * buff,int length)
{
 
 memring->head = 0;
 memring->tail = 0;
 
 memring->length = length;
 memring->pring  = buff;
 
 memring->dataLengthInRing = memDataLengthInRing;
 memring->ringIsEmtpy      = memRingIsEmpty;
 memring->ringIsFull       = memRingIsFull;
 memring->dataPushRing     = memDataPushRing;
 memring->dataPopRing      = memDataPopRing;
}

文章评论0条评论)

登录后参与讨论
我要评论
0
8
关闭 站长推荐上一条 /2 下一条