I want to read sonsor data every few minutes and draw a graph with this data. The graph should include the data of the last 96 measurements.
The graph and everything is ready and good to go - but how to code the buffer?
I need an array with 96 float values - when I add a 97. value, the first one should be dropped. If I add another one - the second should be dropped.
I'll never search in that array - just read the values in a fixed order.
How to realise that? I was thinking about doing it "manually" - I mean, when I add a value, I count up - but once I reach 97 I would need to reorder the whole array everytime I add a new value.
You don’t need to re-order the array, and that is by far the LEAST efficient way to do it. You simply need to wrap the array index back to 0 using the mod operator % whenever you reach the end of the buffer.
float data[96];
put_index = 0;
get_index = 1;
// clear the data
for (int i=0; i<96; i++)
data[i] = 0.0;
// Add a new sample
data[put_index] = readSample();
put_index = (put_index + 1) % 96;
// plot the data
for (int i=0; i<96; i++)
{
int index = (i + get_index) % 96;
float point = data[index];
plotPoint(point);
}
get_index = (get_index + 1) % 96;
This will plot points 1-95, then 0 on the first pass, point 2-95, then 0-1 on the second pass, 2-95, then 0-2 on the third pass, etc. so you always plot the last 96 samples in order.
Try to imagine your buffer is a length of pigeon-holes.
You wouldn't shuffle all the contents of the individual slots up one place when you reached the end.
There was a good explanation of the Arduino serial buffers on Hackaday recently.
There is a circular buffer in Yet Another Software Serial. The code may be more accessible than the HardwareSerial library - it's pretty much the same buffer code.
How many decimals fo you need? Consider multiplying your result by 10 or 100 and storing the results as ints. Uses less ram. That keeps your results in an array of 96 ints instead of 96 floats. Usually too much accuracy is a waste anyway.