创建实例
//创建环形缓存区
#define RBUFF_SET_LEN 8 //缓存最大长度设置
typedef struct
{
unsigned char headpos;//头
unsigned char tailpos;//尾
unsigned char len; //长度
unsigned char rbuf[RBUFF_SET_LEN];//接收缓存数据区
}ringBuf_st;
ringBuf_st ringBuf;//创建一个ringBuf的缓冲区
void RingBuff_Init(ringBuf_st *ringBuf_me)//初始化相关信息
{
ringBuf_me->headpos = 0;
ringBuf_me->tailpos = 0;
ringBuf_me->len = 0;
memset(&ringBuf_me->rbuf[0],0,RBUFF_SET_LEN);
}
unsigned char RingBuff_Write(ringBuf_st *ringBuf_me,unsigned char writeData)//往环中写入一个数据
{
if(RBUFF_SET_LEN<=ringBuf_me->len) //判断缓冲区是否已满
{
return 0;//写入失败
}
ringBuf_me->rbuf[ringBuf_me->tailpos++]=writeData;
ringBuf_me->tailpos %= RBUFF_SET_LEN;//防止越界非法访问//限制在一个RBUFF_SET_LEN长度内
ringBuf_me->len++;
return 1;//写入成功
}
unsigned char RingBuff_Read(ringBuf_st *ringBuf_me,unsigned char *readData)//从环中读取一个数据
{
if(0==ringBuf_me->len)//判断空
{
return 0;//读取失败
}
*readData = ringBuf_me->rbuf[ringBuf_me->headpos++];//先进先出FIFO,从缓冲区头出
ringBuf_me->headpos %= RBUFF_SET_LEN;//防止越界非法访问
ringBuf_me->len--;
return 1;//读取成功
}