0
点赞
收藏
分享

微信扫一扫

基于Android的记单词App系统的设计与实现

王远洋 04-11 08:30 阅读 2

用C代码实现环形缓冲区(ring buf)

概述

因嵌入式项目需要,串口接收的数据有很高的周期性发送频率,原方式通过查询接收标志再接收会导致数据丢失和硬件buf溢出等问题,因此考虑开足够大的环形缓冲区(ring buf)实现,接收中断中仅实时的进行buf写操作,应用程序进行循环查询处理,将数据处理和数据接收解耦合,本文采用VS Code + Gcc编译器编写了测试验证程序,对ringbuf进行了测试,参考文章链接,并非照抄,而是在原文基础上进行了改进,并封装成单独的.c文件。

环境介绍

本文测试代码时在VS Code环境下进行了编写和调试,编译工具用的mingw64,详细配置方法就不做介绍了,主要介绍我遇到的一个问题:单个C程序可正常编译,但多个C程序编译报错(未定义的函数名),主要问题是launch.json 和 tasks.json 不对,参考文章,我的配置如下:

launch.json(没改)

 {
    // 使用 IntelliSense 了解相关属性。 
    // 悬停以查看现有属性的描述。
    // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": []
}

tasks.json

该文件主要修改了 “ f i l e " 参数为: " {file}" 参数为:" file"参数为:"{cwd}\*.c”,以编译当前工程目录下的所有C文件

{
	"version": "2.0.0",
	"tasks": [
		{
			"type": "cppbuild",
			"label": "C/C++: gcc.exe 生成活动文件",
			"command": "C:\\mingw64\\bin\\gcc.exe",
			"args": [
				"-fdiagnostics-color=always",
				"-g",
				//"${file}", //默认仅编译当前打开的单个文件
				"${cwd}\\*.c",//编译当前目录下的所有C文件
				"-o",
				"${fileDirname}\\${fileBasenameNoExtension}.exe"
			],
			"options": {
				"cwd": "${fileDirname}"
			},
			"problemMatcher": [
				"$gcc"
			],
			"group": "build",
			"detail": "编译器: C:\\mingw64\\bin\\gcc.exe"
		}
	]
}

注意

这2个文件不是自己编写的,生成方法如下:
打开项目文件夹->终端->配置默认生成任务->选择gcc,之后会自动生成,我们只需要修改部分内容即可

代码

三个文件,main.c为主程序,ringbuf.c和ringbuf.h

ringbuf.c


#include "ringbuf.h"

/* ******************************************
* 环形缓冲区初始化函数 InitRingBuff函数参数说明:
*   参数1 buf :指向ringbuf的结构体指针
*   参数2 size :buf大小,单位字节
*   参数3 over_mode :写入覆盖模式
*        0-   当buf满时阻塞写,并丢弃最新数据
*        1-   当buf满时覆盖写,并丢弃最早的数据
***************************************** */
void InitRingBuff(ringfifo *buf, unsigned int size,int over_mode)
{
    buf->pHead = (char *)malloc(size * sizeof(char));
    memset(buf->pHead, 0, size);
    buf->pValidRead = buf->pHead;
    buf->pValidWrite = buf->pHead;
    buf->pTail = buf->pHead + size;
    buf->used_space = 0;
    buf->free_space = size;
    buf->overwrite = over_mode; 
    printf("pread is %d \t pwrite is %d \t used_space is %d \n",buf->pValidRead,buf->pValidWrite,buf->used_space);
}

// 向缓冲区写数据
int WriteRingBuff(ringfifo *buf,char *pdata, unsigned int len)
{
    if (buf->pHead == NULL )
    {
        printf("WriteRingBuff: RingBuff is not Init!\n");
        return -2;
    }
    if (len > buf->pTail - buf->pHead)
    {
        printf("WriteRingBuff: ring buf is too small\n");//每次写入数据不能超过buf总长度,否则认为buf开的不够
        return -1;
    }
    if ((len > buf->free_space) && (buf->overwrite != 1))
    {
        printf("WriteRingBuff: New add data is too long\n");//只有在覆盖模式才可写入超过剩余空间的数据,否则无法写入
        return -1;
    }
    // 若新增的数据长度大于写指针和尾指针之间的长度
    if (buf->pValidWrite + len > buf->pTail)
    {
        int PreLen = buf->pTail - buf->pValidWrite;
        int LastLen = len - PreLen;
        memcpy(buf->pValidWrite, pdata, PreLen);
        memcpy(buf->pHead, pdata + PreLen, LastLen);
        buf->pValidWrite = buf->pHead + LastLen; // 新环形缓冲区尾地址
    }
    else
    {
        memcpy(buf->pValidWrite, pdata, len); // 将新数据内容添加到缓冲区
        buf->pValidWrite += len;              // 新的有效数据尾地址
    }
    if ((len > buf->free_space) && (buf->overwrite == 1))//覆盖写
    {
        buf->pValidRead = buf->pValidWrite;
        buf->used_space = buf->pTail - buf->pHead; 
        buf->free_space = 0;
    }
    else{//未覆盖
        buf->used_space += len; 
        buf->free_space -= len;
    }
    return 1;
}

// 从缓冲区读数据
int ReadRingBuff(ringfifo *buf, char *pdata, unsigned int len)
{
    if (buf->pHead == NULL )
    {
        printf("ReadRingBuff: RingBuff is not Init!\n");
        return -2;
    }
    if (len > buf->used_space)
    {
        printf("ReadRingBuff: Read data is too long\n");
        return -1;
    }
    if (len == 0)
    {
        return 1;
    }
    if (buf->pValidRead + len > buf->pTail)
    {
        int PreLen = buf->pTail - buf->pValidRead;
        int LastLen = len - PreLen;
        memcpy(pdata, buf->pValidRead, PreLen);
        memcpy(pdata + PreLen, buf->pHead, LastLen);
        buf->pValidRead = buf->pHead + LastLen;
    }
    else
    {
        memcpy(pdata, buf->pValidRead, len);
        buf->pValidRead += len;
    }
    buf->used_space -= len;
    buf->free_space +=len;
    return len;
}

ringbuf.h

#ifndef __RINGBUF_H_
#define __RINGBUF_H_

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

typedef struct
{
    char *pHead;       // 环形缓冲区首地址
    char *pValidRead;  // 已使用环形缓冲区首地址
    char *pValidWrite; // 已使用环形缓冲区尾地址
    char *pTail;       // 环形缓冲区尾地址
    unsigned int used_space;  //环形缓冲区有效数据个数
    unsigned int free_space; //环形缓冲区剩余空间
    int overwrite;// 1- overwrite
} ringfifo;

void InitRingBuff(ringfifo *buf, unsigned int size,int over_mode);
int WriteRingBuff(ringfifo *buf,char *pdata, unsigned int len);
int ReadRingBuff(ringfifo *buf, char *pdata, unsigned int len);

#endif

main.c


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "ringbuf.h"

int main()
{
    char c;
    int len;
    int readLen = 1;
    char readBuffer[10];
    int i = 0;
    ringfifo buf1;
    int r;

	char* strbuff = (char*)malloc(100 * sizeof(char));
    buf1.overwrite = 1;
    InitRingBuff(&buf1,10,1);
    printf("Please enter a character,VER 0.4\n");

    while (1)
    {
        fgets(strbuff,100,stdin);
        printf("strlen is %d\n",strlen(strbuff)-1);
        if(strlen(strbuff)>1)
        {
            switch (*strbuff)
            {
            case 'R':
                r = ReadRingBuff(&buf1,readBuffer, readLen);
                if (r > 0)
                {
                    for (i = 0; i < readLen; i++)
                    {
                        printf("%c ", (char)readBuffer[i]);
                    }
                    printf("\n");
                    printf("pread is %d \t pwrite is %d \t used_space is %d free space is %d BUF:",buf1.pValidRead,buf1.pValidWrite,buf1.used_space,buf1.free_space);
                    for (i = 0; i < buf1.pTail - buf1.pHead; i++)
                    {
                        printf("%c ", (char)*(buf1.pHead+i));
                    }
                    printf("\n");
                }
                break;

            default:
                WriteRingBuff(&buf1,strbuff, strlen(strbuff)-1);
                printf("pread is %d \t pwrite is %d \t used_space is %d free space is %d BUF:",buf1.pValidRead,buf1.pValidWrite,buf1.used_space,buf1.free_space);
                for (i = 0; i < buf1.pTail - buf1.pHead; i++)
                    {
                        printf("%c ", (char)*(buf1.pHead+i));
                    }
                printf("\n");
                break;
            }
        }
    };


    return 0;
}

测试说明

程序运行后输入除了”R“以外的任意字符,按回车后写入buf,输入R时从buf读取1个字节,初始化buf时需设置覆盖/阻塞模式,测试结果如下:
在这里插入图片描述

工程代码下载

举报

相关推荐

0 条评论