Ok,
So I've been looking into circular buffers, an interesting and useful concept I can use in the future.
For my current project I think I'll stick with the code I have:
HDD Motor Scrollwheel - working but room for improvement]
@jfjlaros Sorry man, thanks for the help but your code is just too advanced for me at this point
I did however write code based on the circular buffer concept. It works and fits my need. I'll give implementing it into my project a thought. See the code below.
Thanks for the input to all for now, I've learned enough.
The only thing I have not figured out is what '% n' does or means. I could not google "%n" so what is that method / notation called? Thanks.
#include <Streaming.h>
#define BUFLEN 5 // Length of buffer
int buf[BUFLEN]; // Define buffer
int writeIndex = 0; // Index at which a new value should be written to
int readFrom; // Start index of reading
long multiplier; // Used in get() to caculate result, long so BUFLEN can be 5 or more
long result; // Returned from get()
int val; // New value to be stored
void setup()
{
Serial.begin(115200);
}
void loop()
{
val = random(1, 7);
put(val);
Serial << "New value has been put in: " << val << endl;
Serial << "The values in sequence of input: " << endl;
Serial << get() << endl;
delay(1500);
}
void put(int item)
{
writeIndex++; // Increment write index
if(writeIndex == BUFLEN) writeIndex = 0; // Set back to zero if 'out of index' is reached
buf[writeIndex] = item; // Save/store value
}
long get() // Long because return can be > 65000
{
readFrom = writeIndex; // Start reading from the index of the last written value
multiplier = 1; // Set multiplier for the first read value
result = 0; // Reset result to zero
for(int i = 0; i < BUFLEN; i++) // Read entries of whole buffer
{
result += buf[readFrom] * multiplier; // Buffer 641, result: 1*1 + 10*4 + 100*6 = 641
multiplier = multiplier * 10;
readFrom--; // Go backward through the buffer
if(readFrom == -1) readFrom = BUFLEN - 1; // If index < 0 got to end
}
return result;
}