【问题标题】:Simple circular buffer: Need to extend function to overwrite old data简单循环缓冲区:需要扩展函数来覆盖旧数据
【发布时间】:2019-10-28 19:03:05
【问题描述】:

我正在尝试实现一个简单的循环缓冲区,并覆盖旧数据(只是尝试使用缓冲区)。 实际上我实现了一个缓冲区,但它没有覆盖旧数据。 当缓冲区已满时,它不会向数组中添加新数据。

我有以下:

//Struct with 8 bytes
typedef struct
{
   int8 data_A;                        
   int16 data_B;
   int8 data_C;
   int32 data_D; 
} MyData_Struct_t

//The Circular buffer struct
typedef struct {
   MyData_Struct_t  myData[10]; // 10 elemtns of MyData_Struct_t
   int8 write_idx
   int8 read_idx
   int8 NrOfMessagesinTheQue
} RingBuffer


static MyData_Struct_t  myDataVariable =  {0}; // Instance of MyData_Struct_t
static RingBuffer myRingBuffer= { 0 };      // Instance of myRingBuffer

myDataVariable.data_A = getData(A);  // Lets' say getData() function is called cyclic and new data is received
myDataVariable.data_B = getData(B);  
myDataVariable.data_C = getData(C);   
myDataVariable.data_D = getData(D); 

// Here I call a function to fill the array with data
writeDataToRingbuffer(&myRingBuffer, &myDataVariable); 

void writeDataToRingbuffer(RingBuffer *pBuf, MyData_Struct_t *Data)
{
   if (10 <= pBuf->NrOfMessagesinTheQue)
   {
        // Buffer is Full
   }

   else if (pBuf->write_idx < 10)
   {
      (void)memcpy(&pBuf->myData[pBuf->write_idx], Data, 
sizeof(MyData_Struct_t));  //myData will be read later by another function

      if ((10 - 1u) == pBuf->write_idx)
      {
         pBuf->write_idx = 0u;
      }

      else
      {
         pBuf->write_idx += 1;
      }

      pBuf->NrOfMessagesinTheQue++;
   }

   else
   {
      // Out of boundary
   }
}

我需要一些想法如何扩展此功能以覆盖旧数据?

非常感谢!

【问题讨论】:

  • 考虑int8 --> uint8_t.

标签: c circular-buffer


【解决方案1】:

如果您只想覆盖最旧的数据,只需使用以缓冲区大小为模的索引:

#define BUFFER_SIZE 10  // size of myData

void writeDataToRingbuffer(RingBuffer *pBuf, MyData_Struct_t *Data)
{
    (void)memcpy(&pBuf->myData[pBuf->write_idx % BUFFER_SIZE], Data, 
         sizeof(MyData_Struct_t));  //myData will be read later by another function

    pBuf->write_idx += 1;
    pBuf->NrOfMessagesinTheQue++;
}

使用此方法,您还可以组合 write_idx 和 NrOfMessageinTheQue,因为您现在不必将索引重置为 0。

【讨论】:

    猜你喜欢
    • 2014-07-21
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    相关资源
    最近更新 更多