i'm currently working on a project where I'm averaging the output of the last 10 to 20 measurements. to do this I'm saving the last 10 values in an array. right shifting the elements to update the data.
The code that I'm using to shift the values:
void shiftvals() {
memmove(&val[1], &val[0], (sizeof(val) / sizeof(val[0]))-1);
for (unsigned int i = 0; i < (sizeof(val) / sizeof(val[0])); i++)
{
Serial.print(val[i]);
Serial.print(",");
}
Serial.println();
}
The code calling the function:
#define ARR_SIZE 10
uint16_t val[ARR_SIZE];
void loop(){
Serial.print("Size of the array:\t");
Serial.println(sizeof(val) / sizeof(val[0]));
shiftvals();
val[0] = (analogRead(A0));
}
Now the problem is that the last few outputs will always be 0, even though the array fills up nicely. When I increase the size of the array the amount of empty spaces also increase.
Output:
396,396,381,462,503,195,0,0,0,0,
472,472,396,381,462,247,0,0,0,0,
495,495,472,396,381,206,0,0,0,0,
435,435,495,472,396,125,0,0,0,0,
I'm seriously confused, what am I doing wrong in the memmove
?
The problem is in your call to memmove. Your sizing is too short.
void shiftvals() {
memmove(&val[1], &val[0], (sizeof(val) / sizeof(val[0]))-1);
// that was only 9 bytes, but val[] is 20 bytes long.
// ...
}
Should read
void shiftvals() {
memmove(&val[1], &val[0], (ARR_SIZE - 1) * sizeof(val[0]));
// ...
}