Sliding last 5 values in array

Good afternoon,

Could you please explain me how I could capture 5 last values of sensor input in Arduino in order to have the oldest value dropped each time a new value comes in. I am fine creating array for that but I can not understand how to slide value in this array in order to have the last value always in the same cell.

Thank you for your help.

Tom

Don’t move readings around, move the index.

tomcat25:
Good afternoon,

Could you please explain me how I could capture 5 last values of sensor input in Arduino in order to have the oldest value dropped each time a new value comes in. I am fine creating array for that but I can not understand how to slide value in this array in order to have the last value always in the same cell.

Thank you for your help.

Tom

As AWOL suggests, consider a circular buffer with an head index or "pointer" to the start of the active 5 entries and a tail pointer to the array entry where the next reading will go.

Thank you both for swift answer. I have limited skill in programming but will look around. Would you have example to provide?

Thank you

you have an array[5] - fine.
you add one variable writePosition
you add one variable readPosition
you increment the respective position - depending what you are doing.

give it a try, it's not so hard.

in Google search for "Ring Buffer C++"

An example

byte anArray[5];

void setup()
{
  Serial.begin(115200);
  while (!Serial);
}

void loop()
{
  static byte index = 0;
  anArray[index++] = random(256);
  if (index == 5)
  {
    index = 0;
  }
  printArray(index);
  delay(2000);  //simulate waiting for another reading
}

void printArray(byte printIndex)
{
  byte count = 0;
  while (count < 5)
  {
    Serial.println(anArray[printIndex++]);
    if (printIndex == 5)
    {
      printIndex = 0;
    }
    count++;
  }
  Serial.println();
}

There is a pretty easy-to-understand example here, too.