#define MEMORY_SIZE 8
int myArray_X[MEMORY_SIZE];
int myArray_Y[MEMORY_SIZE];
int currentIndex; // will refer to the latest (x,y) points (or -1 if no data)
boolean arrayFull; // false while we have not filled in the array once. true after.
void addNewXY(int x, int y)
{
++currentIndex; // go to the next available position where we will store data
if (!arrayFull && (currentIndex >= (MEMORY_SIZE-1))) arrayFull = true; // have we filled the array?
// check for bounds. we don't want to write beyond our array bounds
currentIndex = currentIndex % MEMORY_SIZE; // or if (currentIndex >= MEMORY_SIZE) currentIndex=0;
myArray_X[currentIndex] = x; // store x
myArray_Y[currentIndex] = y; // store y
if (arrayFull) {
Serial.print("\tFULL - index ="); Serial.println(currentIndex);
} else {
Serial.print("\tNOT FULL - index ="); Serial.println(currentIndex);
}
}
void setup() {
Serial.begin(115200);
currentIndex = -1;
arrayFull = false;
// stuff the array with data
for (int i = 0; i < 100; i++) {
Serial.print(i);
addNewXY(i, 2 * i);
}
}
void loop() {}
Well the oldest entry if the array has been filled in is the next one. If the next one is beyond the bounds of the array then it's 0. So basically (currentIndex+1)%MEMORY_SIZE
Once the array has been filled
currentIndex Is the current data
(currentIndex+1)%MEMORY_SIZE is the oldest (8th in your case)
(currentIndex+2)%MEMORY_SIZE is the one before the oldest (7th in your case)
(currentIndex+3)%MEMORY_SIZE is the one before (6th in your case)
Etc
If the array has not be filled, the oldest one is entry 0
Im assuming its not efficient or possible to bump all the values across so you can just refer to array[0] and array[7]
Well with 8 values it would be fast so if you really need an easy access later to all the data then that can be done, it saves from doing some other modulo math later.
i know this is a ball of string question, but is there a ball park figure to how big an array can be(assuming using UNO or the like), where you would start to question whether another approach should be used.
last question i promise, ive bugged you enough for one day.
The first is to move the values across when a sample comes in. To do this, don't write a loop - use memcpy from the standard library.
The second and more efficient is to use a circular buffer. First sample goes in 0, second on 1, etc, and when you get to the end you wrap around.
To keep (for instance) a running sum, you subtract the value you are about to overwrite from the running sum, and then add the new value that you are writing. Be sure to zero your array right at the start!