Ringbuffer - First In - First out

Hi Ladies and Gentlemen,

I've the following problem.

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.

Please help me. :slight_smile:

Look in the HardwareSerial class in the core. There they've implemented a very nice ring buffer.

Basically you need an array with 96 elements and two pointers, one to point to the next place to read and one to point to the next place to store.

PS. To find the HardwareSerial class, look in the folder where you installed the IDE. Arduino/hardware/arduino/cores/arduino/

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];
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.

Ray L.

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.

10 Minutes and I got 2 answers - both correct and understandable for me!

You guys are aweseome. I’ll go for lunch and program that after.

Thank you so far - I’ll let you know if I got it. :slight_smile:


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.


i coded it out - like Ray told me to do - worked perfect for my needs

thank you all

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.

Usually too much accuracy is a waste anyway.

Using floats would mean LESS accuracy. Always more accuracy with fixed point and integers.